2011-01-20 79 views
4

++发现我的代码中的内存泄漏的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.

如果我注释掉“字符串FOO ;”它没有检测到任何东西。

我应该以某种方式重新分配富?

回答

10

您正在运行_CrtDumpMemoryLeaks()太早,它报告string体的泄漏。只有在所有本地对象都被销毁后才能运行它。

自动换行的所有有意义的工作在一个单独的功能

void doStuff() 
{ 
    string variable; 
} 

或添加嵌套范围:

int main() 
{ 
    { 
     string variable; 
    } 
    _CrtDumpMemoryLeaks(); 
    return 0; 
} 
+0

这显然是不可能的,如果您有任何基于堆栈的对象! `_CrtDumpMemoryLeaks()`来自* C *运行时库;它并没有预料到破坏者...... – 2011-01-20 14:42:28

+2

@Oli:不可能如何?锐利示范如何做到这一点。 – 2011-01-20 14:46:01

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; 
} 
9

你应该调用程序/块终止后_CrtDumpMemoryLeaks。要做到这一点,最好的办法是有 CRT调用其本身在程序终止,如_CrtDumpMemoryLeaks msdn article说:

_CrtDumpMemoryLeaks频繁调用在程序执行 结束,以确认所有内存 应用程序分配已经被释放。该 函数可以在程序终止自动 通过使用 _CrtSetDbgFlag功能上 转动_crtDbgFlag标志 的_CRTDBG_LEAK_CHECK_DF位字段被调用。

通过调用它,你做的方式,它会检测到富的泄漏,因为它的析构函数 尚未被称为自该执行单元还未结束。