Possible Duplicate:
Does free(ptr) where ptr is NULL corrupt memory?
I'm writing a C function that frees a pointer if it was malloc()
ed. The pointer can either be NULL (in the case that an error occured and the code didn't get the chance to allocate anything) or allocated with malloc()
. Is it safe to use free(ptr);
instead of if (ptr != NULL) free(ptr);
?
gcc
doesn't complain at all, even with -Wall -Wextra -ansi -pedantic
, but is it good practice?
It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.
free(NULL) is perfectly legal in C as well as delete (void *)0 and delete[] (void *)0 are legal in C++.
No. The free() function takes a pointer. In C functions arguments are passed by value. So the pointer passed to free() cannot be changed by the function.
Yes, when you use a free(px); call, it frees the memory that was malloc'd earlier and pointed to by px. The pointer itself, however, will continue to exist and will still have the same address. It will not automatically be changed to NULL or anything else.
Quoting the C standard, 7.20.3.2/2 from ISO-IEC 9899:
void free(void *ptr);
If
ptr
is a null pointer, no action occurs.
Don't check for NULL
, it only adds more dummy code to read and is thus a bad practice.
However, you must always check for NULL
pointers when using malloc
& co. In that case NULL
mean that something went wrong, most likely that no memory was available.
It is good practice to not bother checking for NULL
before calling free
. Checking just adds unnecessary clutter to your code, and free(NULL)
is guaranteed to be safe. From section 7.20.3.2/2 of the C99 standard:
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. Ifptr
is a null pointer, no action occurs.
As noted in the comments, some people sometimes wonder if checking for NULL
is more efficient than making a possibly unnecessary function call. However, this:
NULL
first even might be a pessimization. For example, if 99% of the time your pointers aren't NULL
, then there would be a redundant NULL
check 99% of the time to avoid an extra function call 1% of the time.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With