dangling pointer, reason for value change after free()?

夙愿已清 提交于 2019-12-01 21:54:34

This is undefined behavior, explanations are just speculation.

I can speculate that maybe you are running a debug version of the C library, and that the debug version of free() does zero the pointed area.

What is done in free depends on the implementation. It is not prohibited to zero out the memory after it's freed.

And what you're doing is undefined behavior.

Doesn't y points to the same address as x, after line

y = x;

If you free x, you will also free the memory pointed by y.

If you are wondering why it prints '0', that undefined behavior, but I've seen it as a practice before, that some programmers, sets the freed area to '0'.

Download this video called "Binky the pointer fun video" (it's not a joke, actually is very educative), and you'll get pointers better.

Michael Burr

The call to free() will put the memory block that had been allocated by malloc() back onto data structures that the C runtime maintains for the heap (in this case something that might be called the 'free-list).

Manipulating the heap data structures might incidentally change what was being pointed to by y (since the program doesn't own the memory anymore, it has no reason to believe the memory shouldn't change).

In a non-debug build of the program, the runtime typically won't do anything specifically to invalidate freed memory, but as I mentioned, it may still make changes as a result of its own bookkeeping (though since the memory doesn't belong to the caller anymore, the runtime is allowed to do whatever it likes).

In a debug build, the runtime will probably explicitly overwrite the memory to a value that is likely to be invalid if the program does use it in the hopes that it will cause a problem that identifies the problem more readily. Usually the value used to overwrite the freed memory block isn't zero, since zero will often not expose a bug (i.e. NULL pointer checks will cause the code to 'handle' the invalid memory access). For example, MSVC's debug heap manager will overwrite freed memory with the value 0xDD (see When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete? for more details).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!