Let’s say I have a pointer and allocate some memory for it. In case malloc
would return a null pointer for whatever reasons, is it considered good practice to free it? Does it change something in this case? Is a check for malloc
returning a null pointer even necessary?
char *some_function()
{
char *ptr = (char *)malloc(sizeof(char) * 10);
if (ptr == NULL)
{
free(ptr);
return NULL;
}
//some operations with the pointer
}
CodePudding user response:
A check for malloc
returning NULL
is definitely necessary, since you cannot use NULL
as a pointer to memory.
On the other hand, free(NULL)
does nothing. (That's guaranteed by the standard.) So you can do that if you want to, but there's absolutely no point. If malloc
returned NULL
, no memory was allocated so there is nothing to free.
The point of free(NULL)
being legal (and doing nothing) is that it lets you call free
on any pointer returned by malloc
, which simplifies resource freeing:
void do_something(unsigned n) {
int* data = malloc(n * sizeof(*data));
if (data) {
// Do something
}
else {
sprintf(stderr, "Couldn't allocate temporary vector of %ud ints\n", n);
}
free(data);
}