c++ - 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 reason of segmentation fault in first case have dynamically allocated memory . trying use memory not allocated. in second case using stack memory. can explain more ? sry bad style of asking doubt , newbie

use new instead of malloc.

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

as vector class non-trivial constructor, struct has non-trivial constructor, can not ignored.

remember delete pointer after using avoid memory leak.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -