Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::edge causing segfault

I'm trying to use the boost graph library, and I'm getting a segfault when I try to use boost::edge(). The full code is available here, but here I've made a minimal program that has the same issue (I'm compiling with "g++ minimal.cpp"):

#include<stdio.h>
#include<boost/graph/adjacency_list.hpp>

using namespace boost;
using namespace std;

typedef adjacency_list<> graph_t;
typedef graph_traits<graph_t>::edge_descriptor edge_descriptor;

int main(){
    graph_t G;
    //add_edge(1,3,G);
    //remove_edge(1,3,G);
    pair<edge_descriptor, bool> res = edge(1,3,G);
    printf("G does %shave an edge 1->3\n", res.second ? "" : "not ");
    return 0;
}

If I uncomment the add_edge, remove_edge lines, The segfault does not occur, and the program prints the expected

G does not have an edge 1->3

but is there a way to avoid such hackery? Thanks!

like image 957
bgschiller Avatar asked Mar 15 '13 02:03

bgschiller


1 Answers

Apparently, the add_edge(1,3,G) call adds vertices to the graph if needed. Your first call is in that case. Then it adds the edge from vertex 1 to vertex 3. Note that after this call, the number of vertices is 4, since the vertices are then indexed from 0 to 3.

The subsequent call to remove_edge(1,3,G) removes the edge that was just added, but leaves the number of vertices unchanged.

The call to edge(1,3,G) on the other hand does not add any vertex to the graph, the boolean in the return is there to state if vertices 1 and 3 are connected or not. There is an access violation is you remove the add_edge because the vertices at index 1 and 3 do not exist.

You can simply initialize the graph with the desired number of vertices:

graph_t G(4);
like image 158
Raffi Avatar answered Sep 26 '22 15:09

Raffi