How to use a C++ string in a structure when malloc()-ing the same structure?
c++, malloc, string, struct
Solution
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.
Problem
I wrote the following example program but it crashes with segfault. The problem seems to be with using `malloc` and `std::string`s 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::string`s? Thanks, Boda Cydo.