I am writing a program that makes an undirected graph and performs BFS on that graph. This graph uses an adjacency list representation, built on-top of a List struct that I had previously built. Anyways, I'm trying to load in the graph from a file then perform BFS on it, but if I perform BFS on a graph (loaded from a file) with over 30 vertices, I get a segfault during a malloc call. If I, however, don't load the graph from file and instead make it by hand (using loops and manually adding vertices/edges), I can have thousands of vertices and 10k+ edges and no segfaults occur at all. This obviously makes me think that something that I'm doing while loading in the graph data is corrupting the heap, but the odd thing is that the malloc call that fails isn't in the function that reads from the file, and the function does correctly translate the input file into a graph data structure, so I am lost. Below is the function that reads in from the input file.
The following is my output on GDB :
Program received signal SIGSEGV, Segmentation fault.
_int_malloc (av=0x7ffff7dd3760 <main_arena>, bytes=24) at malloc.c:3766
3766 malloc.c: No such file or directory.
I would like to stress that there has to be something inside of this function that is causing my heap to corrupt, even though the corruption doesn't show until a bit later.
Graph readFile(char * fn) {
FILE * fp = fopen(fn, "r");
char line[80];
if(fp == NULL) {
fprintf(stderr, "Error : Invalid Filename Argument");
exit(1);
}
fgets(line, 80, fp);
int order = 0;
sscanf(line, "%d", &order);
if(order <= 0) {
fprintf(stderr, "Error parsing input file, order < 0");
exit(1);
}
printf("%d\n", order);
Graph new_graph = newGraph(order);
while(fgets(line, 80, fp) != NULL)
{
int origin = -1;
int terminus = -1;
sscanf(line, "%d %d", &origin, &terminus);
printf("%d %d\n", origin, terminus);
if(origin > 0 && terminus > 0 && origin <= order && terminus <= order) {
addEdge(new_graph, origin , terminus);
}
else {
break;
}
}
fclose(fp);
//printGraph(stdout, new_graph);
return new_graph;
}
If I call this function to load a graph, then perform BFS, the following malloc call fails in a function inside the List class
void append(List L, int data) {
if(L == NULL) {
fprintf(stderr, "Error : L null in append\n");
exit(1);
}
printf("Before\n");
Node * new_node = malloc(sizeof(Node)); <-- SEGFAULTS
printf("After\n");
if(new_node == NULL) {
fprintf(stderr, "Error : Malloc Fail in Append");
}
new_node->data = data;
// printf("Midway\n");
if(L->num_nodes == 0) {
L->front_node = new_node;
L->back_node = new_node;
L->num_nodes++;
return;
}
new_node->prev = L->back_node;
L->back_node->next = new_node;
L->back_node = new_node;
L->num_nodes++;
}