Reputation: 1869
I'm trying to use gtree
, which comes from glib
.
I'm getting wrong values(always 0) in s variable while iterating it like that:
gboolean iter_all(gpointer key, gpointer value, gpointer data) {
int *s = (int *)value;
printf("\n%s%d \n", (char *)key, *s);
return FALSE;
}
GTree* t = g_tree_new((GCompareFunc)g_ascii_strcasecmp);
readFilec(t);
g_tree_foreach(t, (GTraverseFunc)iter_all, NULL);
I set up the tree like this:
void readFilec(GTree *tree)
{
FILE *fp = fopen("cfg/file.csv", "rb" );
char * line = NULL;
size_t len = 0;
ssize_t read;
if (fp == NULL)
exit(EXIT_FAILURE);
char *p1;
int p2;
while ((read = getline(&line, &len, fp)) != -1)
{
printf("%s", line);
p1 = strtok(line, "|");
p2 = (int)atoi(strtok(NULL, "|"));
g_tree_insert(tree,(gpointer ) g_strdup(p1), (gpointer ) &p2);
printf("-%s%d ", p1, p2);
}
if (line)
free(line);
//exit(EXIT_SUCCESS);
}
The file which I read looks like that:
cfg/file.csv
AA1.E|1
AA2.E|2
Upvotes: 0
Views: 122
Reputation: 4325
The comment already identified the issue (you are inserting a pointer to a local stack variable into the tree), but there are still a few less serious issues. When storing int
in a GTree
, it's better to use it as the pointer value directly, e.g.:
gboolean iter_all(gpointer key, gpointer value, gpointer data) {
int s = (int) value;
printf("\n%s%d \n", (char *)key, s);
return FALSE;
}
...
g_tree_insert(tree, (gpointer) g_strdup(p1), (gpointer) p2);
To avoid memory leaks, you also need to specify a destroy function to free the string keys:
GTree* t = g_tree_new_full((GCompareFunc) g_ascii_strcasecmp,
NULL, g_free, NULL);
Upvotes: 1