C++:std:在main()中设置内存泄漏

Kna*_*bax 1 memory memory-leaks stl set

在使用许多标准模板库容器(如std :: set或std:vector)的Microsoft Visual C++(VS 2008/2010)中,您将遇到内存泄漏:

#include <set>
#include <stdlib.h>
#include <crtdbg.h>
#define _CRTDBG_MAP_ALLOC

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    printf("I'm leaking\n");

    std::set<int> s;

    _CrtDumpMemoryLeaks();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

运行程序后,您将获得如下输出:

Detected memory leaks!
Dumping objects ->
{209} normal block at 0x005E9C68, 20 bytes long.
 Data: <h ^ h ^ h ^     > 68 9C 5E 00 68 9C 5E 00 68 9C 5E 00 CD CD CD CD 
{208} normal block at 0x005E9C20, 8 bytes long.
 Data: <  ;     > F8 FE 3B 00 00 00 00 00 
Object dump complete.
Run Code Online (Sandbox Code Playgroud)

这是解决方案:只需将定义括在括号中,如下所示:

int _tmain(int argc, _TCHAR* argv[])
{
    printf("I'm not leaking any more\n");

    {
        std::set<int> s;
    }
    _CrtDumpMemoryLeaks();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是一个奇怪的行为,我想知道这是微软编译器中的错误还是某些STL问题?我想这是前者.如果有人在Linux系统上尝试过这个,那么知道它会很有趣......

Car*_*rum 5

第一个例子是如何泄漏的?s仍然在范围内,所以当然它仍然有与之相关的记忆.返回后,您必须进行内存泄漏检测调用_tmain才能获得有效的答案.

在你的第二个例子中,s超出范围并且已被破坏,因此它没有更多的内存与它相关并不奇怪.

您只需要在代码中有意义的位置调用泄漏检查程序.