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
When you are calling malloc
you are getting a pointer. The runtime library needs to keep track of the malloc
ed memory. Typically malloc
does not store the memory management structures separated from the malloc
ed memory but in one place. So a malloc
for x bytes in fact takes x+n bytes, where one possible layout is that the first n bytes are containing a linked list struct with pointers to the next (and maybe previous) allocated memory block.
When you free
a pointer then the function free
could walk through it's internal memory management structures and check if the pointer you pass in is a valid pointer that was malloc
ed. Only then it could access the hidden parts of the memory block. But doing this check would be very time consuming, especially if you allocate a lot. So free
simply assumes that you pass in a valid pointer. That means it directly access the hidden parts of the memory block and assumes that the linked list pointers there are valid.
If you free
a block twice then you might have the problem that someone did a new malloc
, got the memory you just freed, overwrites it and the second free
reads invalid pointers from it.
Setting a free
d pointer to NULL
is good practice because it helps debugging. If you access free
d memory your program might crash, but it might also just read suspicious values and maybe crash later. Finding the root cause then might be hard. If you set free
d pointers to NULL
your program will immediately crash when you try to access the memory. That helps massively during debugging.