In Multidimensional arrays as class member with arbitrary bounds I was advised I should use a vector of vectors of ints to represent a dynamic 2D array in my array-backed graph object. However, I'm getting segmentation faults whenever I try to run my code. GDB points to the line where a variable is defined as the arraygraph
type; I presume that means I did something wrong specifying the type of edges
. Here is the class definition:
class arraygraph {
private:
public:
void open(char *filename);
bool exists(int nodeid);
int node_count(void);
int weight(int nodea, int nodeb);
void print();
private:
int count;
vector <vector <int> > edges; //A vector of vectors! [Inception Noise]
};
All the methods of this object are defined (funny how you can compile with prototypes that haven't been filled out...). The code compiles without errors or warnings. Why's it segfaulting?
EDIT:
Here's some disassembler output:
163 int main(int argc, char *argv[]) {
main(int, char**):
00401c86: lea 0x4(%esp),%ecx
00401c8a: and $0xfffffff0,%esp
00401c8d: pushl -0x4(%ecx)
00401c90: push %ebp
00401c91: mov %esp,%ebp
00401c93: push %ebx
00401c94: push %ecx
00401c95: sub $0x20,%esp
00401c98: mov %ecx,%ebx
00401c9a: call 0x402350 <__main>
164 arraygraph thegraph;
00401c9f: lea -0x18(%ebp),%eax (this is where the problem occured according to GDB)
00401ca2: mov %eax,%ecx
00401ca4: call 0x403e90 <arraygraph::arraygraph()>
So apparently the segfault happened before the arraygraph
was constructed? I don't know what to make of this.
EDIT:
The entirety of main()
is as such:
int main(int argc, char *argv[]) {
arraygraph thegraph;
thegraph.open(argv[1]);
return 0; //Added this after I noticed I'd omitted it - didn't fix anything
}
And here's arraygraph::open()
:
//Only call .open() once. A second call will leave the old graph's dessicated corpse around the edges of the new one.
void arraygraph::open(char *filename){
int count;
int x, y;
tomgraph loader;
loader.open(filename);
count=loader.node_count();
//delete edges;
//edges = new vector <vector <int> >;
for (x=1; x <= count; x++) {
for (y=1; y <= count; y++) {
int weight;
if (loader.is_connected(x,y,&weight) || loader.is_connected(y,x,&weight)) {
edges[x-1][y-1]=weight;
} else {
edges[x-1][y-1]=0; //0 represents "no edge"
}
}
}
}
But according to the disassembler this never gets called anyway.
EDIT:
Full code here. Umm... I think it's saying it worked? Lemme try a different machine...
EDIT:
Nope. Similar segfault after compiling on a completely separate Linux machine.
EDIT:
Just to confirm, I commented out the call to thegraph.open()
. Didn't fix it.