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

Jax-p picture Jax-p · Mar 1, 2016 · Viewed 8.3k times · Source

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;
}

Answer

Ashish Ahuja picture Ashish Ahuja · Mar 1, 2016

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.