On 2017/3/11 6:32, onkel.jack@xxxxxxxxxxx wrote:
Its quite simple:
free de-allocates the memory the pointer is pointing to.
BUT: it does NOT change the value of p. So p still holds the address.
It has nothing to do with free(). In Martin's example the pointer is
invalidated even without any function calls.
(free cant change the variable it got hand over since c calls goes by copy, not by reference ....)
The undefined behavior results from using the pointer still holding the address while a subsequent malloc can re-use the memory.
Let's think about a scenario where you can't play with virtual memory
addresses directly and all pointers are actually sort of handles (think
about Java without GC) and pointer comparison is done by comparing the
virtual addresses that are known only by the runtime. A pointer is then
invalidated as soon as it is free()'d - it could magically become null
or whatever referring another object.
Therefore its a good practice always set the pointer to NULL directly after freeing it.
No. I set it to 0xDEADBEEF instead. I discover bugs, not hide them.
--
Best regards,
LH_Mouse