I’m grappling with an issue in my code where nodes are being counted multiple times, especially when there are duplicates with the same name. I want to ensure that each node is counted only once, regardless of whether nodes with identical names exist. I tried using “return NULL” instead of “return node”, but it ended up triggering a memory error. Any suggestions on how to fix this?
graph.c:
#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;
}
graph.h:
graph.h
#ifndef GRAPH_H
#define GRAPH_H
typedef struct node {
struct node **out_edges;
unsigned num_edges;
char *name;
} node_t;
typedef struct graph {
node_t **nodes;
unsigned count;
char *name;
} graph_t;
graph_t *init_graph(const char *);
void free_graph(graph_t *);
node_t *get_node_from_graph(graph_t *, const char *);
void add_edge_to_node(node_t *, node_t *);
#endif
Correct output:
- num nodes: 6
- num edges: 12
- indegree: 0 – 4
- outdegree: 0 – 5
The Output I get:
- num nodes: 10
- num edges: 12
- indegree: 0 – 4
- outdegree: 0 – 5
Tagore is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.