I'm having many difficulties with c language. I'm currently trying to generate a graph from a txt file according to this question: why am I getting segmentation fault on the code below?
The generate_nodes method is working after I made the changes according to the best answer I had. But now I'm having issues in generate_edges method.
graph node type:
#ifndef Graph_Structure
#define Graph_Structure
#include <stdbool.h>
struct Graph_Node{
int id;
char node_name[100];
bool path;
struct Graph_Node* next;
struct Graph_Node* edge;
struct Graph_Node* next_edge;
};
typedef struct Graph_Node graph_node;
#endif
generate_edges method:
int generate_edges(graph_node **graph, const char *file_name){
FILE *fp = fopen(file_name, "r");
if(fp == NULL)
{
fprintf(stderr, "Error opening file %s: %s\n", file_name,
strerror(errno));
return 0;
}
char line[1024];
size_t linenmr = 0;
while(fgets(line, sizeof line, fp))
{
linenmr++;
// getting rid of the newline
line[strcspn(line, "\n")] = 0;
if(strlen(line) > 12)
continue; // resume reading, skip the line
char *sep;
long int dst = strtol(line, &sep, 0);
sep++;
long int src = strtol(sep, &sep, 0);
//search for edge in graph
//printf("dst: %ld ", dst); printf("src: %ld\n", src);
add_edge(graph, src, dst);
}
return 1;
}
add_edge method:
void add_edge(graph_node **graph, int src, int dst){
graph_node* temp = *graph;
graph_node* temp2 = *graph;
while(*graph != NULL){
if((*graph)->id == src){ //search for edge source
//printf("AQUI: %d\n", (*graph)->id);
while(temp2 != NULL){
if(temp2->id == dst){ //search for edge destination
//printf("AQUI 2: %d\n", temp->id);
(*graph)->next_edge = (*graph)->edge;
(*graph)->edge = temp2;
break;
}
temp2 = temp2->next;
}
temp2 = temp;
break;
}
*graph = (*graph)->next;
}
*graph = temp;
}
print_graph method:
void print_graph(graph_node* graph){
if(graph == NULL){
return;
}
else{
graph->path = true;
printf("%d ", graph->id);
puts(graph->node_name);
printf("\n");
while(graph->edge != NULL){
if(graph->edge->path == false)
print_graph(graph->edge);
graph->edge = graph->next_edge;
}
}
}
what is happening is that when I try to print the graph I get stuck in an infinite loop inside "while" from method print_graph which doesn't make sense since I initialize all node's edges with null. It's like a node didn't have an edge with null value, but here is my insert code updated:
void insert_node(graph_node** node, graph_node data){
graph_node* temp = (graph_node*)malloc(sizeof(graph_node));
temp->id = data.id;
strcpy(temp->node_name, data.node_name);
temp->node_name[sizeof(temp->node_name) - 1] = 0;
temp -> edge = NULL;
temp -> next_edge = NULL;
temp -> path = false;
temp -> next = *node;
*node = temp;
}