c++ - 二维数组错误: Vector index beyond memory allocation

标签 c++ arrays vector

谁能帮我理解为什么会出现这个错误。

我有一个包含数字的文件 5 4
9 1 5 3
14 12 3 10
9 7 10 14
8 5 0 3
14 13 6 14
8 11

我将这些数字添加到二维 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 }

当我尝试获取最后一行中的最后 2 个数字时,出现错误:

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 << 数据[i-1].size();显示 2 个元素,这是我所期望的,但它仍然给我超出目标内存分配错误的索引。

似乎如果我超出了 data[number][0],那就是错误发生的时候。 有人可以向我解释为什么会这样吗?

感谢您的帮助。

使用 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.

最佳答案

我看到的问题是 i 没有在这里初始化:

int i, j = 0;

您初始化了j,但没有初始化i。所以稍后当您使用 i 时,该值是不可预测的。

解决方案当然是这样做:

int i = 0; int j = 0;

但正如我的评论向您建议的那样,不要使用无关的变量进行计数或获取 vector 中的最后一个元素。如果 vector 不为空,则 vector::back() 函数返回对 vector 中最后一项的引用。

关于c++ - 二维数组错误: Vector index beyond memory allocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29441349/

相关文章:

c++ - 在 `if constexpr` block 内声明的变量范围

c++ - 如何从其方法中删除对象?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c++ - 1.exe : Microsoft C++ exception: std:out_of_range at memory location 0x0012fb8c中0x77e4bef7的未处理异常

c# - 在 C# 中将子数组作为数组传递

javascript - 如何将数组的元素添加到另一个对象并计数

c++ - Exception C++ 第 1 章第 1 部分中的 copy() 算法如何使用?

c++ - 在容器中查找派生对象

java - 在多线程环境中使用什么; vector 或数组列表

c++ - 类 std::vector 没有名为的成员