Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does free(ptr) where ptr is NULL corrupt memory?

People also ask

What happens if I try to free a null pointer?

It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

What will happen if we will do int * ptr NULL?

int * pInt = NULL; To check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer related code e.g. dereference pointer variable only if it's not NULL.

Does null pointer use memory?

A NULL pointer doesn't allocate anything. If you have a definition like this: int *x = NULL; That means the variable x , which points to an int , doesn't point to anything.

What happens when malloc 0?

The result of calling malloc(0) to allocate 0 bytes is implementation-defined. In this example, a dynamic array of integers is allocated to store size elements. However, if size is 0, the call to malloc(size) may return a reference to a block of memory of size 0 instead of a null pointer.


7.20.3.2 The free function

Synopsis

#include <stdlib.h> 
void free(void *ptr); 

Description

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

See ISO-IEC 9899.

That being said, when looking at different codebases in the wild, you'll notice people sometimes do:

if (ptr)
  free(ptr);

This is because some C runtimes (I for sure remember it was the case on PalmOS) would crash when freeing a NULL pointer.

But nowadays, I believe it's safe to assume free(NULL) is a nop as per instructed by the standard.


All standards compliant versions of the C library treat free(NULL) as a no-op.

That said, at one time there were some versions of free that would crash on free(NULL) which is why you may see some defensive programming techniques recommend:

if (ptr != NULL)
    free(ptr);

If ptr is NULL, no operation is performed.

says the documentation.


I remember working on PalmOS where free(NULL) crashed.


free(ptr);
ptr=NULL;
free(ptr);/*This is perfectly safe */

You can safely delete a NULL pointer. No operation will be performed in that case.In other words free() does nothing on a NULL pointer.


Recomended usage:

free(ptr);
ptr = NULL;

See:

man free

     The free() function deallocates the memory allocation pointed to by ptr.
     If ptr is a NULL pointer, no operation is performed.

When you set the pointer to NULL after free() you can call free() on it again and no operation will be performed.


free(NULL) is perfectly legal in C as well as delete (void *)0 and delete[] (void *)0 are legal in C++.

BTW, freeing memory twice usually causes some kind of runtime error, so it does not corrupt anything.