【问题标题】:Segmentation fault while creating an adjacency list创建邻接列表时出现分段错误
【发布时间】:2012-11-08 13:47:17
【问题描述】:

我正在为图形结构创建一个邻接列表。下面是我的代码 sn-p 当我在 gdb 中运行时,给出“程序收到信号 SIGSEGV,分段错误。std::_List_node_base::hook () 中的 0x0040340f”错误。有人可以指出代码中的错误。

struct graph{
    list<int> vertex;
}*v;

list<int>::iterator it;
cin>>num_vertices;

v = new  graph[num_vertices];

if (v == 0)
    cout << "Error: memory could not be allocated";

for(i=1;i<=num_vertices;i++)
{
    cin>>num_connected;
    for(j=1;j<=num_connected;j++)
    {
        cin>>m;
        (v+i)->vertex.push_back(m);
    }
}
for(i=1;i<=num_vertices;i++)
    for(it= (v+i)->vertex.begin();it!= (v+i)->vertex.end();it++)
        cout<<*it<<"->";

【问题讨论】:

  • 你有没有尝试在gdb中一步步运行,看看是哪一行导致了错误?
  • 您可以在 gdb 中使用 backtrace 或简单地使用 bt 来查看导致错误的调用。并且不要使用v+i,使用v[i]

标签: c++ pointers struct


【解决方案1】:

C++ 数组是从零开始的,因此应该使用[0][num_vertices-1] 进行索引。如果您将循环更改为从 0 变为 num_vertices-1

for(i=0;i<num_vertices;i++)

您的代码应该可以工作。

当前的故障可能是由于循环的最后一次迭代取消引用 (v+num_vertices) 造成的,这是您数组之外的内存。写入您尚未分配的内存会产生未定义的行为,因此段错误不会令人惊讶。

【讨论】:

    【解决方案2】:

    我没有看到任何错误,我编译了你的程序(只是声明了你正在使用的变量)并且它工作正常

    #include <iostream>
    #include <list>
    
    using namespace std;
    
    struct graph{
            list<int> vertex;
    }*v;
    
    int main ()
    {
        int num_vertices = 0;
        int num_connected = 0;
    
        list<int>::iterator it;
        cin>>num_vertices;
    
        v = new  graph[num_vertices];
    
        if (v == 0)
            cout << "Error: memory could not be allocated";
    
        for(int i=0;i<num_vertices;i++)
        {
            cin>>num_connected;
            for(int j=1;j<=num_connected;j++)
            {
                int m;
    
                cin>>m;
                (v+i)->vertex.push_back(m);
            }
        }
        for(int i=0;i<num_vertices;i++)
            for(it= (v+i)->vertex.begin();it!= (v+i)->vertex.end();it++)
                cout<<*it<<"->";
    
    }
    

    【讨论】:

    • 如果我从 1 而不是 0 初始化 i 循环,代码将不起作用 ideone.com/S18Ky9
    • @risabh,这是正确的,因为数组索引运行 [0,n) 而不是 [1,n]
    • 感谢您指出错误。如果您能告诉我这是否是制作邻接列表的好方法,我会很高兴?
    • @risabh,这是完全不同的问题,单独发布
    猜你喜欢
    • 2021-12-10
    • 2014-01-25
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    相关资源
    最近更新 更多