繁体   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