I’ve a situation like the following, and I’m not sure whether or not the std::string elements of the struct leak memory or if this is ok. Is the memory allocated by those two std::strings deleted when free(v) is called?
struct MyData
{
std::string s1;
std::string s2;
};
void* v = malloc(sizeof(MyData));
…
MyData* d = static_cast<MyData*>(v);
d->s1 = "asdf";
d->s2 = "1234";
…
free(v);
Leak or not?
I’m using the void-pointer because I have another superior struct, which consists of an enum and a void-pointer. Depending on the value of the enum-variable, the void* will point to different data-structs.
Example:
enum-field has EnumValue01 => void-pointer will point to a malloc’d MyData01 struct
enum-field has EnumValue02 => void-pointer will point to a malloc’d MyData02 struct
Suggestions for different approaches are very appreciated, of course.
There is a leak indeed. free doesn’t call MyData destructor (after all it’s a C function which doesn’t know anything about C++ stuff). Either you should use new/delete instead of malloc/free:
or call destructor by yourself:
as sharptooth noted you can’t directly use memory allocated by malloc as a MyData struct without initialization, so you have to do it by yourself as well. To initialize MyData using already allocated memory you need to use placement new (see in the code above).