Why does this cause a memory leak?

Started by
2 comments, last by DividedByZero 7 years, 9 months ago

Hi guys,

I am confused as to why this reports an eight byte memory leak?

 #define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include<vector>
 
class Test
{
public:
 Test() {}
 ~Test() {}
private:
};
 
std::vector<Test> vectorTest;           // This line causes a leak
 
int main()
{
 #ifdef _DEBUG
  _CrtDumpMemoryLeaks();
  _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
 #endif
 
 return 0;
}


Detected memory leaks!

Dumping objects ->

{154} normal block at 0x00810E98, 8 bytes long.

Data: < > E0 F2 09 00 00 00 00 00

Object dump complete.

Removing the std::vector line stops the leak.

Is there a 'special' way to clean up vectors that I am unaware of?

Thanks in advance :)

Advertisement

The vector is a global variable, so it's constructed before main and destructed after main. You're checking for live allocations during main, which is before the vector has been destructed.

Don't use globals and this problem goes away.

I think this is because your std::vector is defined and lives at global scope. It gets destroyed when the application exits (at the end of/after main returns), but you check for memory leaks while the application is still running (inside main).

EDIT: Ninja Hodgman.

Hello to all my stalkers.

Ah, ok.

Makes sense. Thanks guys :)

This topic is closed to new replies.

Advertisement