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 吗?
最佳答案
您运行 _CrtDumpMemoryLeaks()
的时间过早,它会将 string
正文报告为泄漏。只有在所有本地对象都可能被销毁后才运行它。
要么将所有有意义的工作包装在一个单独的函数中
void doStuff()
{
string variable;
}
或添加嵌套范围:
int main()
{
{
string variable;
}
_CrtDumpMemoryLeaks();
return 0;
}
关于c++ - 字符串导致内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4748391/