I have a General question about memory management in my c++ code. The compiler complains that there is a potential memory leak when I replace a pointer to an object with an new pointer to an object that I have initialized dynamically on the stack. Example:
int* foo(int* h){
int* b = new int(5);
b = h; //Memory leak here. How do I delete b without creating a dangling pointer?
return b;
}
I then use this function to change the state of a pointer
int i = 1;
int* c = &i;
foo(c);
So my question is I have a class that has a function similar to the one above.
when can I delete b from the foo function?
delete b;
would this go into the destructor (which would not help me, as I am using function foo loads of times. so the heap would get used up possibly….? )
If I have not provided enough info above. Please let me know.
Since this is a general question, my preferred general approach would be to use a smart pointer handled using RAII within your class.
The smart pointer encapsulates the raw pointer, and handles required memory management for you – when your class is destructed, whatever pointer value is held therein at the time will get cleaned up without you having to manually delete it. When you assign a new value to the smart pointer, it auto-deletes the existing value for you, if any.
boost::scoped_ptr as a class member ought to work well for you here.
There also seems to be confusion here about what’s on the stack and what’s on the heap. You will not use up the stack simply because you are calling
fooover and over (unless you recurse intofoounbounded, in which case you will eventually run out of stack space). Your local variablebis on the stack, but it points to memory that is allocated usingnewon the heap. When you exitfoo, the stack is reset for the calling function – the stack memory used forbis now available for the next function it calls – but you still need to retain ownership (and eventually release) the heap memory to whichbpointed.EDIT: some sample code should clarify smart pointer approach