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

前端 未结 4 2147
孤街浪徒
孤街浪徒 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:21

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

    No. free just free the allocated space pointed by its argument (pointer). This function accepts a char pointer to a previously allocated memory chunk, and frees it - that is, adds it to the list of free memory chunks, that may be re-allocated.
    The freed memory is not cleared/erased in any manner.

    You should not dereference the freed (dangling) pointer. Standard says that:

    7.22.3.3 The free function:

    [...] Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

    The above quote also states that freeing a pointer twice will invoke undefined behavior. Once UB is in action, you may get either expected, unexpected results. There may be program crash or core dump.

提交回复
热议问题