heap corruption when leaving scope with unique_ptr

Go To StackoverFlow.com

3

I face a problem similar to void pointer returned from function heap corruption

The similarity is that I get "Heap corruption" message when leaving the scope where unique_ptr is used.

Here the code:

void CMyClass::SomeMethod ()
{
  std::unique_ptr<IMyInterface> spMyInterface;
  spMyInterface.reset(new CMyInterfaceObject()); // CMyInterfaceObject is derived from IMyInterface

  any_list.push_back(spMyInterface.get()); // any_list: std::list<IMyInterface*>

  any_list.clear(); // only clears the pointers, but doesn't delete it

  // when leaving the scope, unique_ptr deletes the allocated objects... -> heap corruption
}

Any idea why this happens?

2012-04-04 07:34
by Robin Holenweger
Is the destructor of IMyInterface declared virtual - Henrik 2012-04-04 07:37
you may want to add the OS and the compiler that you are using - Alessandro Teruzzi 2012-04-04 07:37
are you certain that any_list.clear() doesn't delete the object? It sounds like the heap corruption is being reported due to a double delete, when the unique_ptr's destructor is called. Try setting a breakpoint ni the destructor for CMyInterfaceObjectmark 2012-04-04 08:04
Sry. Yes, destructor is virtual. Using WinXP, VS2010, SP1. any_list is a std::list object -> I'll double check double deletio - Robin Holenweger 2012-04-16 11:12
-> turns out this is not of a problem (no double deletion), as this is only a list of pointers which doesn't automatically destroy objects the pointers point to (as expected) - Robin Holenweger 2012-04-16 11:29
Heap corruption can also occur if you write past the end (or beginning) of an array, and will usually not show an error until you new or delete something - Mooing Duck 2012-05-17 20:15


3

std::unique_ptr is a smart pointer that retains sole ownership of an object through a pointer and destroys that object when the unique_ptr goes out of scope.

In your case, you have declared std::unique_ptr<IMyInterface> spMyInterface; inside of SomeMethod() so as soon as the execution leaves the scope of SomeMethod() your object gets destroyed.

Take a look at unique_ptr

2013-07-03 12:16
by flazzari
OK, but how does this explain heap corruption - ancajic 2017-02-09 16:27
Ads