For a class
or struct
such as your example
, the correct answer is use new
not malloc()
to allocate an instance. Only operator new
knows how to call the constructors for the struct
and its members. Your problem is caused by the string member not having ever been constructed.
However, there are rare cases where it is important that a particular patch of memory act as if it holds an instance of a class. If you really have such a case, then there is a variation of operator new
that permits the location of the object to be specified. This is called a "placement new" and must be used with great care.
void *rawex = malloc(sizeof(example)); // allocate space
example ex = new(rawex) example(); // construct an example in it
ex->data = "hello world"; // use the data field, not no crash
// time passes
ex->~example(); // call the destructor
free(rawex); // free the allocation
By using placement new, you are obligated to provide a region of memory of the correct size and alignment. Not providing the correct size or alignment will cause mysterious things to go wrong. Incorrect alignment is usually quicker to cause a problem but can also be mysterious.
Also, with a placement new, you are taking responsibility for calling the destructor by hand, and depending on the origin of the memory block, releasing it to its owner.
All in all, unless you already know you need a placement new, you almost certainly don't need it. It has legitimate uses, but there are obscure corners of frameworks and not everyday occurrences.