C++: std:main() 中设置内存泄漏
在 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 系统上尝试过这个,那么了解一下会很有趣......
In Microsoft Visual C++ (VS 2008/2010) using a number of Standard Template Library containers like std::set or std:vector you will run into memory leaks with this:
#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;
}
After you run the program, you'll get some output like this:
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.
Here is the solution to this: Just enclose the definition in braces like this:
int _tmain(int argc, _TCHAR* argv[])
{
printf("I'm not leaking any more\n");
{
std::set<int> s;
}
_CrtDumpMemoryLeaks();
return 0;
}
It's a strange behavior and I'm wondering if this is a Bug in Microsoft Compilers or some STL-Problem? I guess it's the former. If maybe anyone tried this on a Linux-System, it would be interesting to know...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个例子是如何泄漏的?
s
仍在作用域内,因此当然它仍然具有与其关联的内存。您必须在_tmain
返回后进行内存泄漏检测调用才能获得有效答案。在第二个示例中,
s
超出范围并已被销毁,因此它没有更多与之关联的内存也就不足为奇了。您只需在代码中有意义的位置调用泄漏检查器即可。
How is the first example a leak?
s
is still in scope, so of course it still has memory associated with it. You'd have to make your memory leak detection call after_tmain
returns to get a valid answer.In your second example,
s
is out of scope and has been destroyed, so it's no surprise that it has no more memory associated with it.You just need to call the leak checker at spots in your code that make sense.