dhulmul
dhulmul

Reputation: 750

Segmentation fault while creating an adjacency list

I am creating an adjacency list for the graph structure.Below is my code snippet which is giving "Program received signal SIGSEGV, Segmentation fault. 0x0040340f in std::_List_node_base::hook ()" error when I run in gdb. Could somebody please point out the error in the code.

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<<"->";

Upvotes: 0

Views: 301

Answers (2)

simonc
simonc

Reputation: 42195

C++ arrays are zero-based so should be indexed using [0] to [num_vertices-1]. If you change your loops to go from 0 to num_vertices-1

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

your code should work.

The current failures are presumably caused by the last iteration of the loops dereferencing (v+num_vertices) which is memory beyond your array. Writing to memory you haven't allocated gives undefined behaviour so a seg fault wouldn't be surprising.

Upvotes: 1

user1773602
user1773602

Reputation:

I don't see anything wrong here, I compiled your program (just declared the variables you are using) and it works fine

#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<<"->";

}

Upvotes: 0

Related Questions