I have been taught in lectures, that calling free()
on a pointer twice is really, really bad. I know that it is good practice, to set a pointer to NULL
To answer your first question,
So why does it not know, whether a pointer it receives through
free()
has been freed yet or not?
because, the specification for malloc()
in C standard does not mandate this. When you call malloc()
or family of functions, what it does is to return you a pointer and internally it stores the size of the memory location allocated in that pointer. That is the reason free()
does not need a size to clean up the memory.
Also, once free()
-d, what happens with the actually allocated memory is still implelentation dependent. Calling free()
is just a marker to point out that the allocated memory is no longer in use by the process and can be reclaimed and e re-allocated, if needed. So, keeping track of the allocated pointer is very needless at that point. It will be an unnecessary burden on the OS to keep all the backtracks.
For debugging purpose, however, some library implementations can do this job for you, like DUMA or dmalloc and last but not the least, memcheck tool from Valgrind.
Now, technically, the C
standard does not specify any behaviour if you call free()
on an already free-ed pointer. It is undefined behavior.
C11
, chapter §7.22.3.3, free()
function
[...] 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()
orrealloc()
, the behavior is undefined.