Search code examples
cpointersmallocfree

How to "free" variable after end of the function?


what is the right way to free an allocated memory after executing function in C (via malloc)? I need to alloc memory, use it somehow and return it back, than I have to free it.

char* someFunction(char* a, char* b) {
   char* result = (char*)malloc(la + 2 * sizeof(char));
   ...
   return result;
}

Solution

  • Use free. In your case, it will be:

    char* result = malloc(la + 2 * sizeof(char));
    ...
    free (result);
    

    Also, if you're returning allocated memory, like strdup does, the caller of your function has to free the memory. Like:

    result = somefunction ();
    ...
    free (result);
    

    If you're thinking of freeing it after returning it, that is not possible. Once you return something from the function, it automatically gets terminated.