I have this question regarding memory allocation and deallocation in c++.
Here is the situation:
I have a method foo which allocates memory and then returns that object:
Object foo () {
Object *a = new Object();
// Do something with this object...
return *a;
}
and another method which uses this returned object:
void bar () {
Object a = foo();
// Do something..
}
And my question is, at which point should i deallocate the memory I have allocated? When i return from the method foo, does the method bar get a copy of that object on its stack, or does it get access to that one object somewhere in memory?
Thanks!
Bart
You can’t deallocate that object. It’s lost. It’s a memory leak. You never should have (dynamically) allocated it in the first place. Your code should have looked like this:
It’s a copy of the still existing inaccessible object.