Visual C++2013 std::字符串内存泄漏

Visual C++ 2013 std::string memory leak

本文关键字:内存 泄漏 字符串 Visual std C++2013      更新时间:2023-10-16

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

附言:这是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:ddvctoolscrtcrtw32stdcppnewaop.cpp (6): TestCpp.exe!operator new[] + 0x9 bytes
[11140]     c:worktestcpptestcpp.cpp (307): TestCpp.exe!MemoryLeakTest + 0xA bytes
[11140]     c:worktestcpptestcpp.cpp (401): TestCpp.exe!wmain + 0x9 bytes
[11140]     f:ddvctoolscrtcrtw32dllstuffcrtexe.c (623): TestCpp.exe!__tmainCRTStartup + 0x19 bytes
[11140]     f:ddvctoolscrtcrtw32dllstuffcrtexe.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:

使用Deleaker尝试了您的代码,但没有发现任何泄漏。

然后尝试了这个代码:

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

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

我认为这是VLD中的一个错误,你可以发现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;
    }
};

啊哈,删除[]被调用了!

调用

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样式指针进行初始化。

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