Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 894
Jax-p Avatar asked Mar 01 '16 08:03

Jax-p


4 Answers

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.

like image 120
Ashish Ahuja Avatar answered Sep 28 '22 01:09

Ashish Ahuja


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.

like image 41
Koshinae Avatar answered Sep 27 '22 23:09

Koshinae


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

char *res;
res = someFunction("something 1", "something 2");
free(res);
like image 43
Igal S. Avatar answered Sep 28 '22 00:09

Igal S.


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

like image 32
ameyCU Avatar answered Sep 28 '22 01:09

ameyCU