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

12,498

Solution 1

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.

Solution 2

In the code that called someFunction.

You also have to make clear in the documentation (you have that, right?!), that the caller has to call free, after finished using the return value.

Solution 3

If you return allocated memory, then it is the caller responsibility to free it.

char *res;
res = someFunction("something 1", "something 2");
free(res);

Solution 4

Well you return it to calling function , then just free the pointer in calling function.

Solution 5

If you mean that the returned value is not needed in the calling function and the function is called due to its side effects then you can just write

free( someFunction( p, q ) );
Share:
12,498
Jax-p
Author by

Jax-p

I like unicorns.

Updated on June 05, 2022

Comments

  • Jax-p
    Jax-p almost 2 years

    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;
    }
    
  • Jax-p
    Jax-p about 8 years
    I didn't mean that like this, but this tip will be useful for me :) thank you
  • Marco13
    Marco13 about 8 years
    This code snippet looks so sketchy, I hope there are no misunderstandings: You should NOT free the memory before returning it!