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

Viewed 19401

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.

5 Answers
Related