Rei
Rei

Reputation: 512

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?

Upvotes: 0

Views: 425

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490148

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.

Upvotes: 1

Dietmar Kühl
Dietmar Kühl

Reputation: 153840

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

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.

Upvotes: 1

Related Questions