簡體   English   中英

2D數組錯誤:向量索引超出了內存分配

[英]2D array error: Vector index beyond memory allocation

有人可以幫助我了解為什么我遇到此錯誤。

我有一個編號為5 4的文件
9 1 5 3
14 12 3 10
9 7 10 14
8 5 0 3
14 13 6 14
8 11

我將這些數字添加到2D向量中:

 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 << data [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::back()函數將返回對向量中最后一項的引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM