when declaring for example a malloc and then checking if it is NULL to see if it has been properly allocated, should I free the memory if it is null, example:
int *p;
p = (int *)malloc(sizeof(int));
if (p == NULL)
{
free(p); //Should I free here or will it create an error?
return NULL;
}
If malloc
returns a null pointer it has failed to allocate anything at all, and there's nothing to free.
With that said, passing a null pointer to free
does nothing, so it's safe.
On a related note, in C you shouldn't really cast the result of malloc
.