【发布时间】:2015-03-31 15:01:09
【问题描述】:
在开发专有应用程序期间。我注意到内存泄漏,与 MS Visual C++ 2013 更新 4 中的 std::string 相关。
看看以下导致内存泄漏的(基本)代码原型:
static std::string MemoryLeakTest()
{
static size_t const test_size = 2002;
std::unique_ptr<char[]> result1(new char[test_size]);
std::string result2(result1.get(), test_size);
return result2;
}
通过以下方式调用它:
std::string const testML = MemoryLeakTest();
std::cout << testML << std::endl;
是我做错了什么,还是 Visual C++ STL 中的内存泄漏?
附:这是显示 VLD 检测到的内存泄漏的 DebugView 输出:
[11140] WARNING: Visual Leak Detector detected memory leaks!
[11140] ---------- Block 3 at 0x00A95620: 2002 bytes ----------
[11140] Leak Hash: 0x1DA884B6, Count: 1, Total 2002 bytes
[11140] Call Stack (TID 9568):
[11140] 0x0FF5C260 (File and line number not available): MSVCR120D.dll!operator new
[11140] f:\dd\vctools\crt\crtw32\stdcpp\newaop.cpp (6): TestCpp.exe!operator new[] + 0x9 bytes
[11140] c:\work\testcpp\testcpp.cpp (307): TestCpp.exe!MemoryLeakTest + 0xA bytes
[11140] c:\work\testcpp\testcpp.cpp (401): TestCpp.exe!wmain + 0x9 bytes
[11140] f:\dd\vctools\crt\crtw32\dllstuff\crtexe.c (623): TestCpp.exe!__tmainCRTStartup + 0x19 bytes
[11140] f:\dd\vctools\crt\crtw32\dllstuff\crtexe.c (466): TestCpp.exe!wmainCRTStartup
[11140] 0x75557C04 (File and line number not available): KERNEL32.DLL!BaseThreadInitThunk + 0x24 bytes
[11140] 0x77C4B54F (File and line number not available): ntdll.dll!RtlInitializeExceptionChain + 0x8F bytes
[11140] 0x77C4B51A (File and line number not available): ntdll.dll!RtlInitializeExceptionChain + 0x5A bytes
[11140] Data:
【问题讨论】:
-
你怎么知道是 std::string 导致了泄漏?
-
您的代码具有未定义的行为,因为您正在读取未初始化的值。
-
你是如何确定这段代码泄露的?
-
@wonkorealtime:该解决方案已使用 Visual Leak Detector 进行了测试,它报告内存已分配但未释放的块。出于某种原因,我不能总是重现它。它有时会发生(?)
-
按照 erol 的建议使用 _CrtDumpMemoryLeaks,我没有从这段代码中得到任何泄漏。
标签: c++ c++11 memory-leaks