Reputation: 3
I have a problem with this code. I can't get my expected answer. I searched for this, but I can't find anything. I can't find my mistake..
Here is my code working with g_hash_table
# include <stdio.h>
# include <glib.h>
# include <stdlib.h>
GHashTable *hash = NULL;
int check_sth_blacklist(char *sth)
{
return g_hash_table_contains(hash,sth);
}
main()
{
hash = g_hash_table_new(g_str_hash,g_str_equal);
char *sth = (char*) malloc(32);
scanf("%s",sth);
g_hash_table_add(hash,sth);
scanf("%s",sth);
printf("%d\n",check_sth_blacklist(sth + sizeof(char)*2));
free(sth);
}
in my input I'm writing:
cde
abcde
I think cde
string will add to g_hash_table. then when I'm asking for string cde
in abcde
it returns me 0 value.
Upvotes: 0
Views: 234
Reputation: 41895
I believe when you pass your malloc'd string to a GHashTable under g_str_hash
, you're turning over control of the string to the hash table -- it's up to it to free it when the time comes, etc. I.e. you shouldn't use that space allocation again!
Create a new string for your comparison:
#include <stdio.h>
#include <glib.h>
#include <stdlib.h>
#include <string.h>
GHashTable *hash = NULL;
int check_sth_blacklist(char *sth)
{
return g_hash_table_contains(hash, sth);
}
int main()
{
hash = g_hash_table_new(g_str_hash, g_str_equal);
char *sth = (char*) malloc(32);
scanf("%s", sth);
g_hash_table_add(hash, sth);
char *nth = (char*) malloc(32);
scanf("%s", nth);
printf("%d\n", check_sth_blacklist(nth + 2));
free(nth);
g_hash_table_destroy(hash);
return 0;
}
Let the hash manage any strings you put into it (key or value), all of which should be independent and freeable when the hash itself is destroyed. When run, this gives me:
bash-3.2$ ./a.out
cde
abcde
1
bash-3.2$
Upvotes: 1