iit2011101
iit2011101

Reputation: 33

vector inside a structure if the object of struct is dynamically created then we cannot push elements in the vector

struct node
{
    vector<int> v;
};  
//case 1:

struct node *t = (struct node *) malloc(sizeof(struct node));  

t->v.push_back(4);// segmentation fault

//case 2:
struct node t;
t.v.push_back(6);

I know the reason of segmentation fault in first case we have dynamically allocated memory . then we are trying to use the memory which is not allocated. In second case we are using stack memory. can you explain it more clearly ? sry for bad style of asking doubt , i am newbie

Upvotes: 2

Views: 578

Answers (2)

Matt
Matt

Reputation: 6050

use new instead of malloc.

The default constructor of the struct is not called when using malloc, then the vector is not initialized.

As vector is a class with a non-trivial constructor, so the struct has a non-trivial constructor, it can not be ignored.

Remember to delete the pointer after using to avoid memory leak.

Upvotes: 4

Mike Crawford
Mike Crawford

Reputation: 2278

What Matt said.

Not only is the vector not initialized, but the region of memory occupied by your struct is not set to anything by malloc. You can't even count on it being cleared to zero, it will be whatever the previous user of that region of memory put there.

 struct node *t( new struct node );

Upvotes: 0

Related Questions