6

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. 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?

Linger
  • 14,942
  • 23
  • 52
  • 79
Joe
  • 1,091
  • 1
  • 13
  • 18
  • Can you show the code that inserts stuff into the vector and the code you refer to which deletes the object that you put in the vector? – Dusty Campbell May 22 '09 at 15:07
  • I can if you're interested, but James and ilproxyil helped me solve the problem. Let me know if you're interested. – Joe May 22 '09 at 15:14

3 Answers3

16

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

See also Q: Shrinking a vector

Community
  • 1
  • 1
James Hopkin
  • 13,797
  • 1
  • 42
  • 71
  • 1
    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 May 22 '09 at 15:09
  • This answer is wrong: [the swap trick only _may_ release the memory](http://stackoverflow.com/q/7829018/560648). – Lightness Races in Orbit Oct 30 '14 at 19:55
8

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.

user83255
  • 514
  • 2
  • 7
0

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
  • 7,631
  • 2
  • 24
  • 30
  • 1
    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 May 23 '09 at 17:09
  • 1
    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 May 23 '09 at 23:53