【发布时间】:2012-04-27 07:23:41
【问题描述】:
我在放置新的标准库字符串时面临内存泄漏。
下面我给出了显示泄漏的代码。
string string1("new string");
char _string[sizeof(string)];
new(_string) string(string1);
使用dbx发现泄漏,如下图所示
Actual leaks report (actual leaks: 1 total size: 52 bytes)
Total Num of Leaked Allocation call stack
Size Blocks Block
Address
========== ====== =========== =======================================
52 1 0x43f68 operator new < std::basic_string<char,std::char_traits<char>,std::allocator<char> >::__getRep < std::basic_string<char,std::char_traits<char>,std::allocator<char> >::basic_string < main
Possible leaks report (possible leaks: 0 total size: 0 bytes)
这是真正的内存泄漏还是 dbx 将其解释为泄漏?
【问题讨论】:
-
您是否在任何地方为
_string调用std::string析构函数? -
你想达到什么目的?也就是说,你为什么使用新的展示位置?您尝试使用这个损坏的解决方案解决的原始问题是什么(我的意思是,placement new 是损坏的解决方案,除非您的代码在没有真正内存管理的环境中执行)?
-
请注意,您的
_string数组不能保证与std::string正确对齐。