This is Minimal Working Example, for the problem I am facingin in my real code.
#include <iostream>
namespace Test1 {
static const std::string MSG1="Something really big message";
}
struct Person{
std::string name;
};
int main() {
auto p = (Person*)malloc(sizeof(Person));
p = new(p)Person();
p->name=Test1::MSG1;
std::cout << "name: "<< p->name << std::endl;
free(p);
std::cout << "done" << std::endl;
return 0;
}
When I compile it and run it via valgrind it gives me error: definitely lost: 31 bytes in 1 blocks
Constraints
- I am bind to use malloc in the example above, as in my real code I use a C library in my C++ project, which uses this malloc internally. So can’t get away from malloc usage, as I don’t do it explicitly anywhere in my code.
- I need to reassign
std::string nameofPersonagain and again in my code.
>Solution :
You must manually call the destructor before free(p);:
p->~Person();
Or std::destroy_at(p), which is the same thing.