mcdoomington
mcdoomington

Reputation: 570

C Glib Hash Not Matching After Loop Insert?

I'm not sure why this glib hash table is unable to match the keys - I am curious to know why. I read a delimited file and insert it into the hash table, it can read the last value, but not the first or any before that.

Any help?

I was reading in a text file in the format:

001$002$Someval
and so on....

And the Code:

FILE *f = fopen(DEFAULT_MSG_CODES, "r");

/* If file does not exist return 1 */
if (f == NULL) {
    return -1;
}

char *line;
char *token;
char *fields[8];
int i;
line = malloc(2048);

 GHashTable* hash = g_hash_table_new(g_str_hash, g_str_equal);

g_hash_table_insert(hash, "000", "test");

while (fgets(line, 2048, f) != NULL) {

    line[strlen(line) - 1] = '\0';
    i = 0;
    token = strtok(line, "$");

    while (token != NULL) {

        fields[i] = token;
        i++;
        token = strtok(NULL, "$");
    }

    printf("cid: %s eid: %s msg %s\n",fields[0],fields[1],fields[2]);
    g_hash_table_insert(hash,fields[0],fields[1]);

}

free(line);

fclose(f);

printf("There are %d keys in the hash\n", g_hash_table_size(hash));
printf("There is a match %s\n", g_hash_table_lookup(hash,"003"));

Upvotes: 0

Views: 119

Answers (1)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215257

If I'm not mistaken, you're clobbering the data you put into the hash table on the next iteration of the loop by overwriting line with a new call to fgets. An easy fix would be to strdup (or g_strdup or whatever the ugly glib name for it is) the strings before you add them to the hash table. But you should really read the glib documentation on this API to find out the ownership contract for the data you pass in, and whether the arguments are just pointers to data it will immediately read, or pointers to objects that will become a permanent part of the hash table.

Upvotes: 1

Related Questions