尝试解决分段错误

时间:2017-01-02 22:53:14

标签: c++ segmentation-fault

我继续在我的C ++代码中遇到分段错误,我已经通过执行线程跟踪了GDB,并且没有看到问题的来源。我的程序从主类AsTheCrowFlies中的Vertex对象列表创建一个Graph对象。 Graph对象的实际创建发生在makeGraph(const std :: vector)中。 makeGraph中问题开始的那一行是我调用另一个函数checkEdges(Map map,const Vertex& To,const& From),它看起来像这样:

  bool Graph::checkEdges(Map &map, const Vertex &To, const Vertex &From) {

      if(map.find(To)!=map.end()) {

        std::vector<Edge> edges = map[To];

        for (auto itr = edges.begin(); itr!=edges.end(); ++itr) {

               if(itr->getDestination()==From)
                  return true;

          }

     }

   return false;

 }

根据GDB的输出,当for循环中的if语句执行并尝试使用Vertex类中的重载==函数时,它看起来如何:

     bool Vertex::operator == (const Vertex &other) const {

        if (name==other.name && latitude==other.latitude && 
         longitude == other.longitude) {

            return true;

         }

    return false; 

   }

它给出错误消息:“无法访问地址0x4a8处的内存&gt;”我在GDB中使用bt命令时的错误消息的完整列表是:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b8f6f3 in std::string::size() const ()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
(gdb) bt
#0  0x00007ffff7b8f6f3 in std::string::size() const ()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#1  0x000000000040a729 in std::operator==<char> (__lhs=" ",
__rhs=<error reading variable: Cannot access memory at address 0x4a8>)
at /usr/include/c++/4.8/bits/basic_string.h:2495

#2  0x000000000041a30d in Vertex::operator== (this=0x671b58, other=...)
at Vertex.cpp:50

#3  0x0000000000415fb7 in Graph::checkEdges (this=0x7fffffffe880,
map=std::unordered_map with 50 elements = {...}, To=..., From=...)
at Graph.cpp:364

#4  0x00000000004157cf in Graph::makeGraph (this=0x7fffffffe880,
input=std::vector of length 50, capacity 50 = {...}) at Graph.cpp:161

#5  0x0000000000414bea in Graph::setVertices (this=0x7fffffffe880,
v=std::vector of length 50, capacity 64 = {...}) at Graph.cpp:38

#6  0x0000000000402b62 in AsTheCrowFlies::menu (this=0x7fffffffe800,
filename=0x7fffffffec48 "cap_cities.txt") at AsTheCrowFlies.cpp:17

#7  0x000000000041a05c in main (argc=2, argv=0x7fffffffe9c8) at main.cpp:24

以下是makeGraph的完整版本(const Vertex输入):

 Map Graph::makeGraph(std::vector<Vertex> input) {

   Map new_graph;

   size_t size, n, mid,index;

   size  = input.size();

   n = size - 1;

   mid = ((size + size%2)/2)-1;

   if (size<1)
return new_graph;


double mean,max,min,median; //double variables for mean, median, maximum, minimum, sum of squares and standard deviation created

    //vector used to hold the distances between adjacent vertices
std::vector<double> dist(size); 


    for (int i = 0; i < size; i++) {

        mean=0.0; //set average/mean to "0"


        if(new_graph.find(input[i])==new_graph.end()) { //if the current Vertex has no map entry, add it here

      std::vector<Edge> edges(size);            
      new_graph[input[i]] = edges;         

        }

       //Create and sort duplicate list with each Vertex moved to 
         the front in turn         

       std:vector<Vertex> list(size);

       list = input;

       sort(list.begin(),list.end(),[&](const Vertex &v1, const Vertex &v2){return findMinDist(input[i].getLatitude(),input[i].getLongitude(),v1.getLatitude(),v1.getLongitude()) < findMinDist(input[i].getLatitude(),input[i].getLongitude(),v2.getLatitude(),v2.getLongitude()) ;}); 


       //Gets mean and fills distance tracking vector


       for (int j = 0; j < size; j++) {

        dist[j]=findMinDist(input[i].getLatitude(),input[i].getLongitude(),input[j].getLatitude(),input[j].getLongitude());     
        mean+=dist[j]/size;//accumulates mean value

            }        


      min = dist[1];



      max = dist[n];


  if(size%2==0) { //calculates median distance value for...

    median = (dist[mid]+dist[mid+1])/2; //...even sized vectors and...

      } else {median = dist[mid];} //...odd sized vectors


     if(mean >= median) { //index value is calucated for...

    index = (mid+1)*(mean-min)/(max-min); //...case where mean is greater than or equal to median and...


      } else {index = (mid+1)*(median-min)/(max-min);}  //...case where mean is less than median and...


  for (int k = 0; k < index; k++) { //

         if(!checkEdges(new_graph,list[0],list[k])){

    new_graph[list[0]].push_back(Edge(list[0],list[k],dist[k]));

         }


         if(k!=0) {

             if(new_graph.find(list[k])==new_graph.end()) {//SEGMENTATION
                                                            //FAULT STARTS 
                                                            //HERE

        std::vector<Edge> edges(size);

                    new_graph[list[k]]=edges;

                    new_graph[list[k]].push_back(Edge(list[k],list[0],dist[k]));

            } else {

        if(!checkEdges(new_graph,list[k],list[0])) {

        new_graph[list[k]].push_back(Edge(list[k],list[0],dist[k]));    

                   }

               }

        }

       }


     dist.clear(); 

   }

return new_graph;       

}

getDestination的签名是

  Vertex& Edge::getDestination() {return destination;}

我看着这个并没有看到为什么会出现分段错误。请帮忙!我已经包含了相关的代码部分,其中似乎发生了错误,但如果您需要更多代码来帮助了解正在发生的事情,请告知我们。

1 个答案:

答案 0 :(得分:0)

最有可能的是getDestination()返回指向无效/无效对象甚至null的指针。

无论如何,我会使用调试器。我会略微调整代码,以便调试和检查对象变得更容易。祝你好运!

       Vertex &edgeFrom = itr->getDestination();
       if(edgeFrom==From)
          return true;