I'm trying to locate suspected memory leaks in someone else's code. I don't have access to the original coder, unfortunately. One thing I noticed in a couple places was malloc being used within a function to create a pointer to data that was then returned at the end of the function. I hadn't seen this sort of thing before, and logically my brain tells me that the pointer can never get freed if it's returned like that. A general example is below.
1 2 3 4 5 6
Data* foo(int size){
Data *bar = (Data*)malloc(size);
// test to make sure allocation worked
// do stuff with bar
return bar;
}
Does *bar get freed up by the return function, or by exiting this function and going out of scope? (I'm almost certain the answer is no...)
Is it up to the caller of foo to free as follows:
1 2 3
Data *myBar = foo(size);
//do stuff with myBar
free(myBar);
Even if you do that, does it free *bar? (again, I'm almost certain the answer is no...)
It's all about who/what is responsible for freeing the allocated memory. In the snippet posted, it would be up to the caller of foo just as you suggested.
Here's a walk-through:
1. foo is called.
2. The pointer bar is created and initialized to an address returned from malloc.
3. The pointer is returned from foo, meaning that the address in bar is copied back to myBar and the pointer, itself, bar, is destroyed.
4. The memory allocated with malloc is pointed to by myBar and still exists; bar is out of scope and gone (the pointer, not what it pointed to).
5. free is called on myBar, which frees the allocated memory. myBar still holds the address of where the allocated memory was and must not be accessed.
6. Eventually, the pointer, myBar, will go out of scope and be destroyed.