问题
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?
回答1:
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.
回答2:
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 by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.
回答3:
Randomly googling turns up http://linux.die.net/man/3/free which states:
If ptr is NULL, no operation is performed.
回答4:
In my opinion, no, at least not in your case.
If you couldn't allocate memory, you should have checked that WAY before the call of free.
来源:https://stackoverflow.com/questions/6084218/is-it-good-practice-to-free-a-null-pointer-in-c