Does free() remove the data stored in the dynamically allocated memory?

前端 未结 4 2143
孤街浪徒
孤街浪徒 2020-12-18 12:46

I wrote a simple program to test the contents of a dynamically allocated memory after free() as below. (I know we should not access the memory after free. I wrote this to ch

4条回答
  •  执念已碎
    2020-12-18 13:20

    As described in gnu website

    Freeing a block alters the contents of the block. Do not expect to find any data (such as a pointer to the next block in a chain of blocks) in the block after freeing it.

    So, accessing a memory location after freeing it results in undefined behaviour, although free doesnt change the data in the memory location. U may be getting 0 in this example, u might as well get garbage in some other example.

    And, if you try to deallocate the memory twice, on the second attempt you would be trying to free a memory which is not allocated, thats why you are gettin the core dump.

提交回复
热议问题