Visual C ++在我的代码中发现内存泄漏,所以我把它缩小到尽可能最简单的测试用例并得到了这个:
#define _CRTDBG_MAP_ALLOC // required
#include <stdlib.h> // to enable MSVC++
#include <crtdbg.h> // memory leak detection
#include <string>
using namespace std;
int main() {
string foo;
_CrtDumpMemoryLeaks();
return 0;
}
输出:
Detected memory leaks! Dumping objects -> {130} normal block at 0x008748A8, 8 bytes long. Data: B4 F9 44 00 00 00 00 00 Object dump complete.
如果我评论出“string foo”;它没有发现任何东西。
我应该以某种方式取消分配foo吗?
答案 0 :(得分:10)
您过早地运行_CrtDumpMemoryLeaks()
,并将string
正文报告为泄漏。只有在所有本地对象都被销毁后才能运行它。
将所有有意义的工作包装在一个单独的函数中
void doStuff()
{
string variable;
}
或添加嵌套范围:
int main()
{
{
string variable;
}
_CrtDumpMemoryLeaks();
return 0;
}
答案 1 :(得分:9)
在程序/块终止后应该调用_CrtDumpMemoryLeaks。最好的方法就是拥有 CRT在程序终止时自行调用,如_CrtDumpMemoryLeaks msdn article:
中所述_CrtDumpMemoryLeaks经常在程序执行结束时调用 验证所有内存分配 该应用程序已被释放。该 函数可以自动调用 在程序终止时打开 _CRTDBG_LEAK_CHECK_DF位域 使用_crtDbgFlag标志 _CrtSetDbgFlag函数。
通过以你的方式调用它,它将检测foo为泄漏,因为它是析构函数 尚未被调用,因为执行块尚未结束。
答案 2 :(得分:2)
当字符串仍然存在时,您正在调用_CrtDumpMemoryLeaks();
- 当然它会检测到该字符串仍然存在!
试试这个:
#define _CRTDBG_MAP_ALLOC // required
#include <stdlib.h> // to enable MSVC++
#include <crtdbg.h> // memory leak detection
#include <string>
using namespace std;
int main() {
{
string foo;
}
_CrtDumpMemoryLeaks();
return 0;
}