views:

540

answers:

3

I have a static std::vector in a class. When I use Microsoft's memory leak detection tools:

_CrtMemState state;
_CrtMemCheckpoint( & state);
_CrtMemDumpAllObjectsSince( & state );

it reports a leak after I insert stuff into the vector. This makes sense to me because new space is allocated when something is inserted into the vector. And, this space isn't deallocated until the program terminates (since the vector is static). Is this right?

In the destructor of the class that contains the vector, I'm deleting the object that I put into the vector. However, the memory that's allocated when the insertion happened is still hanging around. Is there anyway to delete this space?

Thanks.

+9  A: 

You can swap the vector with an empty one - this will release the memory.

See also Q: Shrinking a vector

James Hopkin
Awesome! That worked. Thanks. I wish I had asked that question earlier, instead of banging my head against the wall for a couple of days. :-)
Joe
+5  A: 

To add to what James wrote. He means to do this:

std::vector<T>().swap(v);

where 'v' is the vector whose memory you want to release.

Thanks for the details.
Joe
A: 

That is just a quirk of Visual Studio. The vector destructor does release the memory, but the memory checking module doesn't always spot it, so it complains. It is a bit of a pain, but nothing to worry about.

Michael J
Not a quirk of VS. His vector was a static. He was checking for leaks before the statics were released by the CRT.
sean e
That's the quirk.VS incorporates a cut-down version of what used to be called Nu Mega Bounds Checker. Older versions of Bounds Checker used to work well, but the version incorporated with VS7.x gets that wrong. It regularly reports non-existent memory leaks in static objects.
Michael J