Reputation: 50
can someone help me understand why i'm getting this error.
I have a file with numbers
5 4
9 1 5 3
14 12 3 10
9 7 10 14
8 5 0 3
14 13 6 14
8 11
I am adding these numbers to a 2D vector:
25 bool function(const char* myfile){
26
27 std::vector< std::vector<int> > data;
28
29 std::ifstream file(myfile);
30 std::string line;
31
32 while(std::getline(file, line)){
33 std::vector<int> lineData;
34 std::stringstream linestream(line);
35
36 int value;
37 while(linestream >> value)
38 {
39 lineData.push_back(value);
40 }
41 data.push_back(lineData);
42 }
43
44 int i, j = 0;
45 int vertexSize = 0;
46 std::vector< std::vector<int> >::iterator row;
47 std::vector<int>::iterator col;
48 for( row = data.begin(); row != data.end(); row++, i++){
49 for(col = row->begin(); col!= row->end(); col++){
50 std::cout << *col << " ";
51 }
52 std::cout << "\n";
53 }
54
55 vertexSize = data[0][0] * data[0][1];
56 start = data[i-1][0];
57 goal = data[i-1][1];
58
59 std::cout << "Vertex Size:" << vertexSize << "\n";
60 std::cout << "Start: " << start << " goal:" << goal << "\n";
61 return true;
62 }
When i try to get the last 2 numbers in the last line, i am getting the error:
5 4
9 1 5 3
14 12 3 10
9 7 10 14
8 5 0 3
14 13 6 14
8 11
Vertex Size:20
Start: 8 goal:7
** Vector<T>::operator[] error: vector index beyond memory allocation!
Unable to recover, no memory allocated
Terminating program
std::cout << data[i-1].size(); Shows 2 elements, which is what I am expecting, yet it is still giving me that index beyond memory allocation error for goal.
It seems that if i go beyond data[number][0], that is when the errors occur. Can someone explain to me why that is happening?
Thank you for your help.
Debugging with gdb:
warning: no loadable sections found in added symbol-file system-supplied DSO at 0x2aaaaaaab000
5 4
9 1 5 3
14 12 3 10
9 7 10 14
8 5 0 3
14 13 6 14
8 11
0 0
Vertex Size:20
Start: 8 goal:7
** Vector<T>::operator[] error: vector index beyond memory allocation!
Unable to recover, no memory allocated
Terminating program
Program exited with code 01.
(gdb) backtrace
No stack.
Upvotes: 0
Views: 184
Reputation: 35440
The issue that I see is that i
is not initialized here:
int i, j = 0;
You initialized j
, but not i
. So later on when you use i
, the value is unpredictable.
The solution of course is to do this:
int i = 0;
int j = 0;
But as my comment suggested to you, don't use extraneous variables for counting, or to get the last element in a vector. If the vector is not empty, then the vector::back()
function returns a reference to the last item in a vector.
Upvotes: 1