Visual C++2013 std::字符串内存泄漏
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中的内存泄漏?
附言:这是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样式指针进行初始化。
我在你的代码片段中没有看到任何内存泄漏。你怎么知道这是内存泄漏?
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏