简体   繁体   中英

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM