Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible memory leak with malloc, struct, std::string, and free

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.

like image 873
j00hi Avatar asked Jul 20 '26 09:07

j00hi


1 Answers

You shouldn't be using malloc() and free() in a C++ program; they're not constructor/destructor-aware.

Use the new and delete operators.

like image 91
unwind Avatar answered Jul 21 '26 22:07

unwind