I wrote the following example program but it crashes with segfault. The problem seems to be with using malloc and std::strings in the structure.
#include <iostream>
#include <string>
#include <cstdlib>
struct example {
std::string data;
};
int main() {
example *ex = (example *)malloc(sizeof(*ex));
ex->data = "hello world";
std::cout << ex->data << std::endl;
}
I can’t figure out how to make it work. Any ideas if it’s even possible to use malloc() and std::strings?
Thanks, Boda Cydo.
You can’t
malloca class with non-trivial constructor in C++. What you get frommallocis 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, usenewYour original code can be forced to work with
mallocas well, by using the following sequence of steps:mallocraw memory first, construct the object in that raw memory second:The form of
newused above is called “placement new”. However, there’s no need for all this trickery in your case.