Iterator / segmentation fault

Hi all,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream>
#include<vector>
#include<string>

using namespace std;

class myclass{
	public:
		myclass();
		~myclass();
	private:
		vector<string> _names;
		void _addNames1();
		void _addNames2();
};


myclass::myclass(){
	_addNames1();
}

myclass::~myclass(){
}

//function to add names to vector. 
void myclass::_addNames2()
{
	static int i = 0;
	string l_name;
	vector<string> l_names;
	for(int i=0;i<2;i++)
	{
		cout<<"Enter a alien name"<<endl;
		cin>>l_name;
		cout<<"Adding alien name "<<l_name<<" to vector"<<endl;
		l_names.push_back(l_name);
	}
	for(vector<string>::iterator l_it2 = l_names.begin(); l_it2 != l_names.end(); l_it2 ++)
	{
		cout<<"Adding the alien name to human names vector"<<endl;
		if(i < 2)
			_names.push_back(*l_it2);
	}
	i++;
}

//again function to add the names to vector
void myclass::_addNames1()
{
	string l_name;
	vector<string>::iterator l_it;
	cout<<"Enter a name"<<endl;
	cin>>l_name;
	cout<<"Adding name "<<l_name<<" to vector"<<endl;
	_names.push_back(l_name);
	_addNames2();
	for(l_it = _names.begin(); l_it != _names.end(); l_it++)
	{
		
		_addNames2();
//seg fault here
		cout<<*l_it<<endl;	
	}
}

int main()
{
	myclass ob1;
}


why does this program give segmentation fault?
can anyone help me with this program?

Thanks in advance
What should be the supposed output for this program? ie; what this program actually should do?
hi wahaj,

This just takes some input, say some names, and prints. Nothing much.

Thanks
Last edited on
In _addNames2() you modify the vector by adding a name to it, potentially causing it to do a memory reallocation. When this happens existing iterators are invalidated, so on line 62 you end up dereferencing an invalid iterator.
Last edited on
hi cire,
isn't there any solution for this? or should i change the program logic itself?
isn't there any solution for this?


The simplest solution would be to use an index instead of an iterator in the loop beginning on line 57. Another possible solution would be to use a container that doesn't suffer from this behavior, such as a deque or list.
Yep using index would be better.
Thanks both of you for your reply.
Topic archived. No new replies allowed.