簡體   English   中英

如何處理數組C ++中的分段錯誤

[英]How to handle segmentation fault in an array C++

我正在創建一個程序,該程序將根據跟蹤頂點信息的集合和表以及從一個頂點到另一個頂點的最短路徑,找到從一個頂點到另一個頂點的最短路徑。 這是使用數組而不是鏈表創建的。

//--------------------------------------------------------------------------
// 'updatepaths' uses the newest vertex which was added to the Set to modify
//  the distances of the remaining vertices (if smaller)
//  in addition to the newly added vertex, it uses the Set, the Vertexinfo
//  and the Shortpath tables
//--------------------------------------------------------------------------

void Paths::updatepaths(int addnode)
{    
  if (done.in(addnode)) //done is a set instance, checks if the value is in the set
  {
    for (int i = 0; i<VERTICES; i++)
    {
      if (shortpath[edgedata[addnode].path[i].vertexto].distance > edgedata[addnode].path[i].weight) //HERE IS THE ISSUE
      {
        shortpath[edgedata[addnode].path[i].vertexto].distance = edgedata[addnode].path[i].weight;
        shortpath[edgedata[addnode].path[i].vertexto].via = addnode;            
      }
    }
  }     
}

我意識到代碼很難閱讀,但是這是我可以想到的唯一相互比較頂點距離的方法-問題是,在if語句中,有時它將嘗試比較不相交的值存在於數組中。

例如, edgedata[addnode].path[0].weight可能不包含任何值-因此,我的程序拋出了訪問沖突(分段錯誤)。 我嘗試在if語句edgedata[addnode].path[i].weight != NULL為0,但不能在運算過程中使用NULL,如果不存在則永遠不會為0。

我應該如何使它不會嘗試比較不存在的值? 謝謝您的幫助。

如果您的邏輯經常碰到NULL對象,則代碼中可能存在較大的設計或實現問題,但是要解決當前問題,最簡單的方法是使用std::array<>::at() ,代替std::array<>::operator[] ,並捕獲它可能生成的out_of_range異常:

try {
  if (shortpath.at(edgedata.at(addnode).path.at(i).vertexto).distance >
      edgedata.at(addnode).path.at(i).weight)
  {
    shortpath.at(edgedata.at(addnode).path.at(i).vertexto).distance =
      edgedata.at(addnode).path.at(i).weight;
    shortpath.at(edgedata.at(addnode).path.at(i).vertexto).via = addnode;
  }
}
catch (std::out_of_range const &oor) {
  std::cerr << "Out of Range error: " << oor.what() << std::endl;
}

或者,您可以按照以下方式在if語句中使檢查短路(我可能在這里錯過了一兩個檢查,所以要當心):

if ((edgedata.size() >= addnode)
 && (edgedata[addnode].path.size() >= i)
 && (shortpath.size() >= edgedata[addnode].path[i].vertexto)
 && (shortpath[edgedata[addnode].path[i].vertexto].distance >
    edgedata[addnode].path[i].weight))
{
  shortpath[edgedata[addnode].path[i].vertexto].distance =
    edgedata[addnode].path[i].weight;
  shortpath[edgedata[addnode].path[i].vertexto].via = addnode;            
}

編寫c ++代碼時,應首先使用c ++編碼風格。 例如,您可以使用std::vector而不是array,然后應使用iterator訪問vector的元素或使用vec.at(i)因為這兩個方法可以檢查超出的邊界,在c中,它具有沒辦法

暫無
暫無

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

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