How to use a C++ string in a structure when malloc()-ing the same structure?

You can’t malloc a class with non-trivial constructor in C++. What you get from malloc is a block of raw memory, which does not contain a properly constructed object. Any attempts to use that memory as a “real” object will fail.

Instead of malloc-ing object, use new

example *ex = new example;

Your original code can be forced to work with malloc as well, by using the following sequence of steps: malloc raw memory first, construct the object in that raw memory second:

void *ex_raw = malloc(sizeof(example));
example *ex = new(ex_raw) example;

The form of new used above is called “placement new”. However, there’s no need for all this trickery in your case.

Leave a Comment