If I have a c program, like:
SomeTypePtr my_type;
my_type = malloc(sizeof(someType));
/* d开发者_开发技巧o 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 have int *a = malloc (sizeof (int))
and a
has 0xdeadbeef
and you execute free (a)
then after execution a
still contains 0xdeadbeef
but after the free
call this memory address is no more reserved for you. Something like you have rented a flat with malloc
used for some time, returned the flat by free
then you might have a duplicate key for the flat, but it is not reserved for you.
Doing a free
on an already free
d memory will result in double free memory corruption.
- It will not make your pointer NULL.
- It will free the memory pointed by the pointer, leaving the pointer set to an unallocated segment of memory.
- If you don't use malloc or calloc between the calls it will give you a Segmentation Fault.
- "Best practice is that a pointer passes out of scope immediately after being freed." means that the pointer should stay on the stack so that it should not be set NULL explicitly because it will eventually go out of scope and be freed.
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()
. Calling free()
twice on the same allocation will result in heap corruption.
SomeTypePtr my_type;
my_type = malloc(sizeof(someType));
/* do stuff */
free(my_type);
my_type = 0; // Throw away the pointer to released memory, so cannot either free it or use it in any way.
/* do a bunch of more stuff */
free(my_type); // OK now - calling free(0) is safe.
精彩评论