简体   繁体   中英

C++ memory leaks with unordered_map

I've discovered that I have a memory leak somewhere in my application but I've been having trouble narrowing it down. I've tried using the function _CrtDumpMemoryLeaks as instructed in this example but it doesn't show file names. So, I've been trying to find the first point of memory leaks (as there seem to be quite a few according to the output) by placing calls to this dump function at various points. It seems that I am getting a lot of them straight away very early in my constructors for objects.

Upon further investigation, I seem to be getting them with definitions for std::unordered_map even to the point where having a simple main function that just declares a local variable has a memory leak.

For example the following code produces a memory leaks:

void main()
{
    _CrtDumpMemoryLeaks(); // executing this line, no memeory leaks found

    std::unordered_map<int, int> intMap;

    _CrtDumpMemoryLeaks(); // executing this line, memeory leaks found
}

I'm completely confused at this point and get the feeling that chasing this is not going to help me find the memory leak that I am originally noticed.

Any help is very much appreciated.

So you expect that std::unordered_map<T> doesn't hold any memory while you are clinging to an object? That seems to be an unreasonable assumption! At the very least, you should destroy the object you created:

int main()
{
    _CrtDumpMemoryLeaks(); // executing this line, no memeory leaks found

    {
        std::unordered_map<int, int> intMap;
    }

    _CrtDumpMemoryLeaks(); // executing this line, memeory leaks found
}

I don't know whether this will release all memory but it has a better chance. The standard C++ library may still keep some memory pooled in its memory allocation mechanism.

What's the definition of a memory leak except "memory that has been allocated and not yet freed"?

If the unordered_map constructor allocates any memory internally, then you have your "leak" right there. Try putting it in its own scope and see if you get the same results.

It only makes sense to call _CrtDumpMemoryLeaks when you have freed everything you've allocated.

As the other answers have stated, you have a unordered_map in scope and this object has allocated memory. Once it's gone, the allocations will go with it. So wrap it in a scope!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM