I'm trying to use GLib as an alternative to write my own datastructures. My objective is to write a simple graph datastructure based on adjacency lists using only glib.
The code right now is the following
#include <glib.h>
#include <glib/gprintf.h>
struct graph
{
GArray * nodes;
};
struct node
{
GArray * neighbors;
gint weight;
GString * label;
};
struct neighbor
{
struct node * dst;
gint weight;
};
struct graph * graph_new(void);
void graph_node_add(struct graph * graph, const gchar * label, gint weight);
void graph_edge_add(struct graph * graph, struct node * src, struct node * dst, gint weight);
struct graph * graph_new(void)
{
struct graph * g = g_new(struct graph, 1);
g->nodes = g_array_new (FALSE, FALSE, sizeof (struct node));
return g;
}
void graph_node_add(struct graph * graph, const gchar * label, gint weight)
{
struct node * node = g_new(struct node, 1);
node->neighbors = g_array_new(FALSE, FALSE, sizeof (struct neighbor));
node->label = g_string_new(label);
node->weight = weight;
graph->nodes = g_array_append_val(graph->nodes, node);
}
void graph_edge_add(struct graph *graph, struct node *src, struct node *dst, gint weight)
{
struct neighbor * neighbor = g_new(struct neighbor, 1);
neighbor->dst = dst;
neighbor->weight = weight;
src->neighbors = g_array_append_val(src->neighbors, neighbor);
}
int main(void)
{
struct graph * G = graph_new();
graph_node_add(G, "u", 10);
graph_node_add(G, "v", 20);
graph_node_add(G, "w", 15);
struct node * n = &g_array_index(G->nodes, struct node, 0);
g_printf("segfaulting here\n");
char * s = n->label->str;
g_printf("LABEL %s\n", s);
return(0);
}
It segfaults when retrieving the GString
from struct node
(around line 59).
Since I'm starting with GLib, any better approaches to handle my objectives are welcom.
Pay attention that I haven written the functions to free the memory, that is just to make the source code smaller in this question.
On linux the code can be compiled with:
gcc `pkg-config --cflags --libs glib-2.0` -o graph graph.c
This happens because in graph_node_add() you end up adding a single pointer to your array, not the data you wanted to add.
Something like this is likely to work:
struct node node;
node.neighbors = g_array_new(FALSE, FALSE, sizeof (struct neighbor));
node.label = g_string_new(label);
node.weight = weight;
graph->nodes = g_array_append_val(graph->nodes, node);