Is it good practice to malloc in the caller function, and then free in the callee function?
Example:
int main() {
int *ptr = malloc(100);
foo(ptr);
return 0;
}
void foo(int *ptr) {
free(ptr);
}
Is it good practice to malloc in the caller function, and then free in the callee function?
Example:
int main() {
int *ptr = malloc(100);
foo(ptr);
return 0;
}
void foo(int *ptr) {
free(ptr);
}
It is valid C code to call malloc
in main
and free
in foo
, but it is not considered best practice.
If allocation and deallocation are done in different, unrelated, functions, then it becomes that much harder to tell if every block of memory obtained from malloc
is actually freed (to prove you don't have a memory leak) or to prove that every pointer passed to free
actually comes from malloc
(which is a requirement for using free).
In your specific context? I'd ask why you could not simply pass int
down by value...
But lets assume you are passing some complicated struct bar
, that has the property of not being a nice stack resident... That's absolutely fine... Just ensure that the function foo(bar*)
is clearly marked as taking responsibility for bar
and that it will fulfil that responsibility by calling free(bar)
later.
That last part is important as many applications have more than just malloc
/free
memory management. Often you will also have memory mapped files, system heaps, perhaps even specialised allocators.
Why this is important is that passing a Bar*
obtained from a memory mapped file to foo(bar*)
is actually illegal, as it is illegal to pass it to free(bar*)
. On some systems this will be ok, nothing bad happens (because you are lucky). On other systems prepare for debugging woes... poor, poor soul.
The important question here is not: Is this good practice? But: Have I ensured each piece of memory is being appropriately managed?
As an aside, to illustrate that your question holds its own answer, I would like to challenge you to use free(...) without passing it a pointer...