Im trying to write a function that counts the nodes, edges etc. Whenever a node with the same name exists the function shouldn’t count it. The problem is that my function counts some nodes twice. Is there a way to fix it? I tried to use return NULL instead of return node but it gives a memory error.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "graph.h"
graph_t *init_graph(const char *name) {
graph_t *graph = calloc(1, sizeof(graph_t));
if (!graph) {
fprintf(stderr, "Not enough memory to allocate for graph %sn", name);
exit(1);
}
graph->nodes = NULL;
graph->count = 0;
graph->name = calloc(strlen(name) + 1, sizeof(char));
strcpy(graph->name, name);
return graph;
}
void free_graph(graph_t *graph) {
while (graph->count--) {
node_t *node = graph->nodes[graph->count];
if (node->num_edges)
free(node->out_edges);
free(node->name);
free(node);
}
free(graph->name);
free(graph->nodes);
free(graph);
}
node_t *get_node_from_graph(graph_t *graph, const char *name) {
// Check if a node with the same name already exists
for (unsigned i = 0; i < graph->count; i++) {
node_t *node = graph->nodes[i];
if (!strcmp(node->name, name)) {
printf("Node %s already exists.n", name);
return node; // Return existing node
}
}
printf("Adding new node: %sn", name); // debug
node_t *node = calloc(1, sizeof(node_t));
node->out_edges = NULL;
node->num_edges = 0;
node->name = calloc(strlen(name) + 1, sizeof(char));
strcpy(node->name, name);
graph->nodes = realloc(graph->nodes, (graph->count + 1) * sizeof(node_t *));
graph->nodes[graph->count++] = node;
return node;
}
void add_edge_to_node(node_t *source, node_t *target) {
source->out_edges = realloc(source->out_edges, (source->num_edges + 1) * sizeof(node_t *));
source->out_edges[source->num_edges++] = target;
}
New contributor
Tagore is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1