Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ code crashing when trying to pass struct [duplicate]

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);

1 Answers

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.

like image 148
Bathsheba Avatar answered Mar 24 '26 05:03

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!