0

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;
    }    
Ivan.2j
  • 27
  • 5
  • Just a side-note: in the case when `p == NULL` ... `free(p);` and `free(NULL);` are equivalent (C passes arguments by value) and well-behaved (they do nothing). – pmg Feb 28 '21 at 12:56

2 Answers2

8

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Should I free memory in C if it is not allocated properly?

You shouldn't, because you can't, because it turns out the question doesn't even make sense.

malloc either gives you a pointer to properly-allocated memory, or it doesn't.
Those two cases are distinct: It either gives you a non-null pointer, or a null pointer.
A null pointer return means that malloc failed, and did not allocate any memory for you.

Suppose that in the process of trying but failing to allocate the memory that you asked for, malloc did partially allocate some memory, or something. Suppose it was your job to free this. How would you do this? You have no way of referring to that memory! When malloc fails, it returns you a null pointer, and a null pointer points, by definition, nowhere.

It doesn't make much sense to pass a null pointer to the free function. Once upon a time, this was an error, and tended to crash. Today, it's harmless: free checks to see if you've handed it a null pointer, and if so, it quietly does nothing.

So in fact, if malloc partially allocates memory or something, then fails, it has to be malloc's job to clean that up automatically, before returning the null pointer to you.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103