I am facing a memory leak in placement new of standard library string.
Below i have given the code where the leak is showing.
string string1("new string");
char _string[sizeof(string)];
new(_string) string(string1);
The leak is found using dbx, and it is shown as below
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)
Is this the real memory leakage or is the dbx intrepreting this as leak?
You still need to call the destructor for the string object you created by placement new.
std::stringallocates the storage for the chars it stores on the heap (unless you specify a custom allocator, which might be what you’re after here), and you’re leaking that. (sizeof(string)is a constant, doesn’t depend on what is stored in the string.)