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 - Unable to make sub reports with Jasper -

scala - play framework: Modules were resolved with conflicting cross-version suffixes -

Passing Variables from AngelScript to C++ -