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

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

    As far as standard C is concerned, it’s just not specified, because it is not observable. As soon as you free memory, all pointers pointing there are invalid, so there is no way to inspect that memory.*)

    Even if you happen to have some standard C library documenting a certain behaviour, your compiler may still assume pointers aren’t reused after being passed to free, so you still cannot expect any particular behaviour.

    *) I think, even reading these pointers is UB, not only dereferencing, but this doesn’t matter here anyway.

提交回复
热议问题