Archived

This topic is now archived and is closed to further replies.

Greg K

Why does this leak?

Recommended Posts

Why does this code say there is a memory leak? More specifically, it says this: Loaded ''C:\WINDOWS\SYSTEM\KERNEL32.DLL'', no matching symbolic information found. Detected memory leaks! Dumping objects -> {27} normal block at 0x00780CC0, 512 bytes long. Data: < > 00 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 Object dump complete. The thread 0xFFF9C197 has exited with code 6684124 (0x65FDDC). The program ''C:\My Documents\Test\Debug\Test.exe'' has exited with code 6684124 (0x65FDDC).
#include <vector>
#include <stdio.h>
using namespace std;

// DEBUG

#include <crtdbg.h>

void main()
{
	vector<int> v;
	for( int i = 0; i < 100; i++)
		v.push_back(i);
	v.clear();
	_CrtDumpMemoryLeaks();
}

Share this post


Link to post
Share on other sites
Because at point of _CrtDumpMemoryLeaks, v is still holding on to a memory block. The standard states that v will grow its memory to accomedate the demand, and may be equal to, or more than the required size. Next, clear/erase or any other form of removing elements from the vector do not free up or reallocate the memory to a smaller block. That is why, at the point of memory leak dump, they report leakage.

Share this post


Link to post
Share on other sites
Quick trick to actually free up a vector''s memory:

vec.swap(vec);


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites
Or add a scope:


void main()
{
{
vector<int> v;
for( int i = 0; i < 100; i++)
v.push_back(i);
v.clear();
}
_CrtDumpMemoryLeaks();
}


[edited by - DerekSaw on October 14, 2003 5:34:10 AM]

[edited by - DerekSaw on October 14, 2003 5:34:36 AM]

Share this post


Link to post
Share on other sites