Thursday, July 9, 2009

Is it safe to free a NULL pointer in C?

It seems GNU or some compiler says free(NULL) will be ignored. Is this a common sense?

Is it safe to free a NULL pointer in C?
Yes, it's safe. The language reference for the c language (and, I believe, c++ language by extension) indicate that no action will be taken.





This is OK in the sense that you can safely (re)free a pointer variable without worrying that it's already been deleted.





That's the language taking care of things just so you don't have to do stuff like


if (x) free(x);


You can just free(x) without worry.
Reply:you are not pointing to anything with null pointer,


this pointer will be useful for typecasting for pointr tyoes etc


not that much danger will be happenned
Reply:You free storage (memory) that you've allocated with malloc(). A NULL pointer isn't pointing at anything. It doesn't make any sense to free a NULL pointer.


No comments:

Post a Comment