Reputation: 703
I have a function foo like
myType** foo(){
myType **array = malloc( .... );
//Do some stuff
return array;
}
Here I have malloced , but did not free it as I am returning it . Will this cause a memory leak ? Should I explicitly free it in the calling function after I use it ?
Upvotes: 2
Views: 1571
Reputation: 326
I had issues about this problem for long time. I suggest you to read this wiki page:
In your case you can use unique_ptr. So you would be able to transfer the ownership of the pointer to the caller function.
unique_ptr<int> callee1()
{
std::unique_ptr<int> p1(new int(5));
return p1;
}
int main()
{
std::unique_ptr<int> result = callee1() ;
(*result)++; // Increase the value stored in the pointer
std::cout << "New Value: " << (*result) << std::endl;
result.reset() ;
}
Hope this code sniper helps you.
Upvotes: 1
Reputation: 30847
Memory leaks are caused by not freeing memory. As long as the memory will get freed at some point, then it isn't leaked. But if the pointer ever gets "lost" or if some sort of dependency loop causes a situation where the memory stays around even after it is no longer useful, then at that point you've created a leak.
Usually in this type of situation, you create a pattern like this:
void* mything_init() {
void *obj = malloc(LEN);
// do some initialization
return obj;
}
void mything_uninit(void* thing) {
// any teardown
free(thing);
}
For every mything
that you _init
, you must eventually call _uninit
on that object. That is your responsibility as the user of that library. While as the writer of that library, you make sure that anything you allocate in the _init
gets properly freed in _uninit
.
This is a C pattern rather than a C++ pattern as malloc() is a C idiom. C++ uses new
and delete
, and this sort of work us usually done in a constructor/destructor pair.
Upvotes: 2
Reputation: 227370
With this type of function, the caller is the "owner" of the resources pointed at by the pointer. So the caller has to either free the resources, or pass them on to someone else who will.
In C++ one would favour returning a type that manages its own resources, for example an std::vector
, or a smart pointer, that both takes care of resource de-allocation and makes the ownership clear.
See this example,and don't worry, read all about copy elision, particularly named return value optimization (NRVO).
std::vector<std::vector<SomeType>> foo()
{
std::vector<std::vector<SomeType>> tmp = ....;
// do some stuff
return tmp;
}
Upvotes: 5
Reputation: 258548
It's a memory leak only if you don't free the memory (regardless where).
In this case, you should free
it after the function is called and you're done with the pointer.
But this is the C way of doing it. In C++ you'd return a smart pointer, and use new
instead of malloc
.
Upvotes: 5