MWright
MWright

Reputation: 1711

C++ pointer and stack memory management

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.

Upvotes: 0

Views: 243

Answers (2)

Steve Townsend
Steve Townsend

Reputation: 54128

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 foo over and over (unless you recurse into foo unbounded, in which case you will eventually run out of stack space). Your local variable b is on the stack, but it points to memory that is allocated using new on the heap. When you exit foo, the stack is reset for the calling function - the stack memory used for b is now available for the next function it calls - but you still need to retain ownership (and eventually release) the heap memory to which b pointed.

EDIT: some sample code should clarify smart pointer approach

class MyClass {
public:
  MyClass() {}  // no explicit init for myPointer needed
  ~MyClass() {} // frees up any pointer held in myPointer, no explicit delete needed

  void Foo(int* c)
  {
     myPointer.reset(c);  // releases any existing value, takes ownership of c
  }

private:
  boost::scoped_ptr<int> myPointer;  // initially empty
};

Upvotes: 2

unwind
unwind

Reputation: 399713

If you really want to replace the pointer's value with a new pointer allocated in the function, I would recommend using a reference:

void SomeClass::foo(int*& h)
{
  delete h;
  h = new int(5);
}

Of course, this will break if you call it with a pointer to an int which is not on the heap, since you can't delete it in that case. So don't do that.

Upvotes: 3

Related Questions