2
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

Borgleader
  • 15,826
  • 5
  • 46
  • 62
iit2011101
  • 33
  • 2
  • FYI, HTML tags dont do anything in posts. SO uses markdown for formatting. (PS: dont use malloc in C++) – Borgleader Dec 16 '14 at 14:07
  • Dynamic allocation is not the reason for the segmentation fault, using `malloc` when you should have used `new` is. – molbdnilo Dec 16 '14 at 14:21

2 Answers2

4

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.

Community
  • 1
  • 1
Matt
  • 6,010
  • 25
  • 36
  • even if use new it will initialize the vector , vector will be empty.thus adding element in vector won't affect the memory already allocated to structure node? – iit2011101 Dec 16 '14 at 14:18
  • @iit2011101: Yes, but it will be a valid empty vector, so `push_back` will work. With `malloc`, you have a jumble of uninitialised bytes being interpreted as an invalid vector, giving undefined behaviour. – Mike Seymour Dec 16 '14 at 14:20
0

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 );
Mike Crawford
  • 2,232
  • 2
  • 18
  • 28