#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
struct A
{
A(char* p)
: p(p)
{}
~A()
{
delete this->p;
}
char* p;
};
int main()
{
A a(new char);
_CrtDumpMemoryLeaks();
}在调试模式下运行后,Visual Studio 2012的输出窗口显示:
Detected memory leaks!
Dumping objects ->
{142} normal block at 0x007395A8, 1 bytes long.
Data: < > CD
Object dump complete.原因是什么?
发布于 2012-12-22 15:47:41
也许在实际调用析构函数之前,它正在转储内存泄漏?尝试:
int main()
{
{
A a(new char);
}
_CrtDumpMemoryLeaks();
}我建议使用标准的(或boost的)智能指针类,如unique_ptr或shared_ptr,而不是直接处理原始指针的新建/删除。
编辑:删除了将指针设置为NULL的建议,因为delete会处理这个问题。
发布于 2012-12-22 15:47:37
在析构函数有机会运行之前,即在代码块结束之前,您正在转储内存。试试这个,看看有什么不同:
int main()
{
{
A a(new char);
}
_CrtDumpMemoryLeaks();
}https://stackoverflow.com/questions/14001029
复制相似问题