简体   繁体   中英

initializing array of string in binary search tree

my node contains an int and a string variable, and I tried using binary search tree. the code is as follow:

struct node{
int a;
string members[5];
};

int main(){
node * root = NULL;
root = (node*)malloc(sizeof(node));
root->members[0] = "aaaaa";
return 0;
}

of course, my code wasn't exactly like that, I made it short in main because I want to show just the problem. it gave me 'access violation writing location'. I tried using 'new node();' instead of malloc and that didn't happen. why is this exactly?

malloc() only allocates memory. It doesn't call the constructor of the object. You could call the constructor on allocated memory using, eg

void* mem = malloc(sizeof(node));
if (mem) {
    node* root = new(mem) node;
    // ...
}

When using new node instead of malloc(sizeof(node) the allocate memory also gets initialized. Using an uninitialized object is undefined behavior.

malloc only allocates raw storage. new allocates raw storage and initializes it to contain a specified type.

If you're allocating only POD types, that distinction is mostly one of wording, with little real difference in what happens.

If you're allocating something like an std::string that has a constructor, there's a world of difference though. If you use new , then your string variables have all been initialized so they're real (albeit, still empty) strings. When you just use malloc , they haven't been initialized at all--they're just chunks of uninitialized raw storage the right size to contain a string . When you try to use them as a string, a quick crash is about the best you can hope for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM