Visual C++ 2013 std::string 内存泄漏

Visual C++ 2013 std::string memory leak

在开发专有应用程序期间。我注意到内存泄漏,与 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 中的内存泄漏?

P.S。这是 DebugView 输出,显示 VLD 检测到内存泄漏:

[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::unique_ptr<char[]> result1(new char[test_size]);

是正确的。棘手的部分是不写 std::unique_ptr<char>,它也会编译并可能导致内存泄漏(unique_ptr 调用 delete 来释放资源。当使用 new[] 初始化时,我们需要指示 unique_ptr 调用正确的 delete[]).

std::string 构造函数调用也正常,不太可能出现内存泄漏。 std::string 可以用相同的方式从 C 风格的指针初始化。

我在您的代码片段中没有发现任何内存泄漏。你怎么知道这是内存泄漏?

用 Deleaker 试过你的代码,没有发现任何漏洞。

然后尝试了这个代码:

while (true)
{
    std::string const testML = MemoryLeakTest();
    std::cout << testML << std::endl;
}

任务管理器显示内存使用情况保持不变:没有泄漏。

我认为这是VLD中的一个bug,你可以发现std::unique_ptr确实释放了内存,调试时进入,看:

~unique_ptr() _NOEXCEPT
    {   // destroy the object
    _Delete();
    }

更进一步:

void _Delete()
    {   // delete the pointer
    if (this->_Myptr != pointer())
        this->get_deleter()(this->_Myptr);
    }
};

更进一步:

void operator()(_Ty *_Ptr) const _NOEXCEPT
    {   // delete a pointer
    static_assert(0 < sizeof (_Ty),
        "can't delete an incomplete type");
    delete[] _Ptr;
    }
};

啊哈,调用了删除[]!