Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ dynamic allocation program crashes

Tags:

c++

malloc

I have a very simple piece of code with 2 structures and one dynamic allocation. The program crashes on the "nume" initialization.

typedef struct{
    int key;
    string name;
} TElement;

typedef struct nod {
   int cheie;
   string nume;
   struct nod *stg, *dr;
} NOD;

when i try to do this

void ABC::inserare_element(TElement e){
    NOD *p, *q;
    int n;
    /* construction nod p*/
    n=sizeof (NOD);
    p=(NOD*)malloc(n);
    p->cheie = e.key;
    p->nume = e.name; // on this line the program crashes

Thanks

like image 653
vladCovaliov Avatar asked Jun 09 '26 06:06

vladCovaliov


1 Answers

malloc() will not invoke the constructor of NOD, meaning the constructor of nume will not have been invoked resulting in an attempt to use std::string::operator= on an unconstructed/uninitialized std::string: use new.

like image 120
hmjd Avatar answered Jun 11 '26 22:06

hmjd



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!