I have this struct:
struct dat {
std::string name;
};
When the following code is run, my program crashes:
dat* x = (struct dat*)malloc(sizeof(struct dat));
x->name = str;
g_signal_connect (button, "clicked", G_CALLBACK (func), &x);
Don't use malloc in C++.
If you need a variable to have dynamic storage duration, use new and delete instead. In short, malloc will not call any constructors, whereas new will. The fact that the std::string constructor is not being called is probably the cause of your crash.
In many cases though, automatic storage duration will suffice, and you can write, simply:
dat foo;
and pass that instance by reference to your functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With