开发者

Memory leaks detected using type char pointers in std::list

开发者 https://www.devze.com 2022-12-26 21:46 出处:网络
why i\'m getting the memory leak errors without allocating or adding any elements to list below. should i just ignore it?

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()
{
    l开发者_开发知识库ist <char*> roots;

    _CrtDumpMemoryLeaks();
}


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();
}


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号