简体   繁体   中英

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

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.

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

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