views:

148

answers:

4

why i'm getting the memory leak errors without allocating or adding any elements to list below. should i just ignore it?

#define CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <list>
using std::list;

int main()
{
    list <char*> roots;

    _CrtDumpMemoryLeaks();
}
+1  A: 

If you do C++, then using std::string instead of char* might be a better practice.

Anyway, you must understand that the container holds pointers to chars, not the chars themselves. So, on destruction, it will free the memory occupied by the pointers, but not the pointed memory.

In short terms, it is up to you to free every char* before destroying/clearing the list.

ereOn
+3  A: 

The list hasn't been destructed yet when you call _CrtDumpMemoryLeaks, so any allocation it has performed is treated as a memory leak. This has nothing to do with the char*: the same thing would happen with list<int>.

_CrtDumpMemoryLeaks simply reports any allocations that haven't been freed yet. It has no way of knowing that the list destructor is yet to run and perform deallocations.

interjay
+11  A: 

You are not giving the roots variable a chance to be destroyed before checking for memory leaks. If roots is destroyed first, you should notice that everything is cleaned up. Try this instead.

#define CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <list>
using std::list;

int main()
{
    {
        list <char*> roots;
    }

    _CrtDumpMemoryLeaks();
}
Matthew T. Staebler
+1  A: 

In general it's better to do

_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF); (You might need other flags too...)

which causes the runtime to dump memory leaks before it exits than to explicitly call _CrtDumpMemoryLeaks. If you do that you can be sure that any local variables still in scope as well as any global variables will have been freed so any reported memory leaks are "real".

John Burton