【发布时间】:2012-01-12 22:22:12
【问题描述】:
在 Microsoft Visual C++ (VS 2008/2010) 中使用许多标准模板库容器,如 std::set 或 std:vector,您将遇到内存泄漏:
#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;
}
运行程序后,你会得到如下输出:
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.
解决方案如下:只需将定义括在大括号中,如下所示:
int _tmain(int argc, _TCHAR* argv[])
{
printf("I'm not leaking any more\n");
{
std::set<int> s;
}
_CrtDumpMemoryLeaks();
return 0;
}
这是一种奇怪的行为,我想知道这是 Microsoft 编译器中的错误还是某些 STL 问题?我猜是前者。如果有人在 Linux 系统上尝试过这个,知道会很有趣......
【问题讨论】:
标签: memory stl set memory-leaks