If I have a c program, like:
SomeTypePtr my_type;
my_type = malloc(sizeof(someType));
/* do stuff */
free(my_type);
/* do a bunch of more stuff */
free(my_type);
Does the calling of 'free' for my_type do any harm? After I call free(my_type), does the pointer become a null pointer once again?
Deallocating a memory area with
free
does not make the contents of the pointer NULL. Suppose that you haveint *a = malloc (sizeof (int))
anda
has0xdeadbeef
and you executefree (a)
then after executiona
still contains0xdeadbeef
but after thefree
call this memory address is no more reserved for you. Something like you have rented a flat withmalloc
used for some time, returned the flat byfree
then you might have a duplicate key for the flat, but it is not reserved for you.Doing a
free
on an alreadyfree
d memory will result in double free memory corruption.Only if you consider destroying your heap "harm".
free()
will not make your pointer null.Without repeating the other answers, it is incumbent on you to null pointers once you have called
free()
. Callingfree()
twice on the same allocation will result in heap corruption.