Search code examples
cpointersbufferfree

Correct usage of free() function in C


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 ?


Solution

  • You should call free only on pointers which have been assigned memory returned by malloc, calloc, or realloc.

    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 keep in mind:

    • Never free memory twice. This can happen for example if you call free on ptr twice and value of ptr wasn't changed since first call to free. Or you have two (or more) different pointers pointing to same memory: if you call free on one, you are not allowed to call free on other pointers now too.

    • 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

    • You should not dereference freed pointer

    • Passing null pointer to free is fine, no operation is performed.