简体   繁体   中英

C++ Memory Leak Using STL Containers

The following code is giving me a memory leak (using Visual Studio):

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <vector>
#include <memory>

struct Listener {};

struct Subject
{
    std::vector<Listener*> listeners;
};

int main(void)
{
    Subject subject;
    _CrtDumpMemoryLeaks();
    return 1;
}

I presume this is because the STL vector container is using memory on the heap when the Subject class is instantiated. How do I ensure that the vector container is destroyed when the program exits? (I've tried deleting the container in the Subject destructor, but that doesn't seem to work).

The vector is destroyed when the program exits, you don't need to ensure it. You do need to ensure that _CrtDumpMemoryLeaks is called after that destruction if you don't want it to report the allocated memory as "leaked":

int main()
{
    { Subject subject; }
    _CrtDumpMemoryLeaks();
    return 1;
}

std::vector<Listener*> listeners; will not free the members of Listeners. You'd have to delete each of the listeners that are inside the vector, using something like:

for (int i = 0; i < listeners.size(); i++) delete listeners[i]

Personally, I avoid such issues by using smart pointers:

std::vector<std::unique_ptr<Listener>> listeners

_CrtDumpMemoryLeaks detects leaks by counting news and making sure they all match. Because subject never goes out of scope, I'm guessing it is counted as an outstanding reference. Try int main(void) {{Subject subject;}_CrtDumpMemoryLeaks(); return 1} int main(void) {{Subject subject;}_CrtDumpMemoryLeaks(); return 1}

Make sure that the Listener destructor destroys everything it needs to. All the STL container does is invoke the destructor of the object it is holding. It is still your responsibility to handle memory in the class itself.

To be more specific, anything declared with a new or malloc in the class must be freed by the destructor. The STL container won't know how to delete that.

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