I wrote a test example in glib:
#undef G_DISABLE_ASSERT
#undef G_LOG_DOMAIN
#include <stdio.h>
#include <string.h>
#include "glib.h"
void function(gchar *key,gchar *value,gint *user_data)
{
// give the count of the number of times the function was called
(*user_data)++;
}
void cache_test()
{
gchar *str1,*str2,*str3;
GCache *cache = NULL;
gint user_data = 0;
g_assert((cache = g_cache_new( (GCacheNewFunc) g_ascii_strup,
g_free, (GCacheDupFunc) g_strdup, g_free, g_str_hash,
g_str_hash, g_str_equal)) != NULL);
g_print("\n g_assert g_cache_new");
str1 = g_cache_insert(cache,"test");
g_print("\n str1 = g_cache_insert(cache,test)");
g_assert(!strcmp("TEST",str1));
g_print("\n g_assert(!strcmp(TEST,str1))");
str2 = g_cache_insert(cache,"test");
g_print("\n str2 = g_cache_insert(cache,test)");
g_assert(!strcmp("TEST",str1));
g_print("\n g_assert(!strcmp(TEST,str1))");
str3 = g_cache_insert(cache,"glib");
g_print("\n str3 = g_cache_inse开发者_JAVA技巧rt(cache,glib)");
g_assert(!strcmp("GLIB",str3));
g_print("\n g_assert(!strcmp(GLIB,str3))");
g_cache_key_foreach (cache,(GHFunc)function,&user_data);
g_print("\n g_cache_key_foreach (cache,(GHFunc)function,&user_data)");
//g_cache_key_foreach would call function twice and make user_data == 2
g_assert(user_data == 2);
g_cache_value_foreach (cache,(GHFunc)function,&user_data);
g_print("\n g_cache_key_foreach (cache,(GHFunc)function,&user_data)");
//g_cache_value_foreach would call function twice and make user_data == 4
g_assert(user_data == 4);
g_cache_remove(cache,str1);
g_print("\n g_cache_remove(cache,str1)");
g_cache_remove(cache,str2);
g_print("\n g_cache_remove(cache,str1)");
g_cache_remove(cache,str3);
g_print("\n g_cache_remove(cache,str1)");
g_cache_destroy(cache);
g_print("\n g_cache_destroy(cache)");
}
int main (int argc,
char *argv[])
{
cache_test();
return 0;
}
Now my test example crashes at str1 = g_cache_insert(cache,"test"); because of null pointer dereferencing. Any help where I could be going wrong?
Edit
I just tried 1 more quick fix to the test code to confirm your suggestion (of the bug in g_ascii_strup). I used the call
cache = g_cache_new((GCacheNewFunc) g_strdup,
g_free, (GCacheDupFunc)g_strdup, g_free, g_str_hash,
g_str_hash, g_str_equal);
ie instead of g_ascii_strup() I used g_strdup... I didn't see any crash. Am I missing anything here?
And is the g_ascii_strup() bug fixed in the latest glib releases? Can I please have the bug number if you are aware of it?
I'd take out the (GCacheNewFunc) and (GCacheDupFunc) casts because they are breaking type safety, and in this case, hiding a bug: g_ascii_strup takes a length parameter which will probably be garbage. Instead make a function with the proper signature, and call g_ascii_strup inside that function. Then you don't need a cast.
I'd guess that's the issue. But if not, what I'd do is get debug symbols on your GLib, and get a backtrace in gdb.
精彩评论