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
, right after having freed it.
However, I still have never heard any explanation as to why that is. From what I understand, the way malloc()
works, it should technically keep track of the pointers it has allocated and given you to use. So why does it not know, whether a pointer it receives through free()
has been freed yet or not?
I would love to understand, what happens internally, when you call free()
on a location that has previously already been freed.
When you use malloc
you are telling the PC that you want to reserve some memory location on the heap just for you. The computer gives back a pointer to the first byte of the addressed space.
When you use free
you are actually telling the computer that you don't need that space anymore, so it marks that space as available for other data.
The pointer still points to that memory address. At this point that same space in the heap can be returned by another malloc
call. When you invoke free
a second time, you are not freeing the previous data, but the new data, and this may not be good for your program ;)