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;
}
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.
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.
If you return allocated memory, then it is the caller responsibility to free it.
char *res;
res = someFunction("something 1", "something 2");
free(res);
Well you return
it to calling function , then just free
the pointer in calling function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With