Correct usage of free() function in C

DDeme picture DDeme · Apr 4, 2015 · Viewed 30.1k times · Source

I am new in C programming language so can you tell me if this is correct way to do.

for example: program points on buffer and i use that pointer as parameter in free() function. So, what problems can this function cause ?

Answer

gmoniava picture gmoniava · Apr 4, 2015

You call free on pointers which have been assigned memory returned by malloc/calloc/realloc only.

E.g.

char* ptr=malloc(10); 

// use memory pointed by ptr 
// e.g., strcpy(ptr,"hello");

free(ptr); // free memory pointed by ptr when you don't need it anymore

Things to remember:

  1. Never free memory twice. This can be done: (1) If you call free on ptr twice and value of ptr wasn't changed since first call to free (2) You have two different pointers pointing to same memory; If you call free on one, you are not allowed to call free on the second pointer now too

  2. When you free a pointer you are not even allowed to read its value; e.g., if (ptr) not allowed after freeing unless you initialize ptr to a new value

  3. Of course you should not also dereference freed pointer

  4. As pointed out by @chqrlie, I will also add here that it is also perfectly OK to pass a null pointer to free, which will just do nothing then