Vala语言中该HashTable代码出现段错误的原因及解决方法
Vala HashTable代码编译警告与运行段错误的原因及解决方法
问题代码
public static void myshowHashTable(HashTable sht){ stdout.printf("Size of sent hashtable: %d", (int)sht.size()); sht.foreach((key,val) => { stdout.printf("Key:%s, value:%s", (string)key, (string)val); } ); } public static void main(string[] args){ HashTable<string,int> ht = new HashTable<string,int>(str_hash, str_equal); ht.insert ("first string", 1); ht.insert ("second string", 2); ht.insert ("third string", 3); myshowHashTable(ht); }
编译警告
myhashtable.vala.c: In function ‘myshowHashTable’: myhashtable.vala.c:45:29: warning: passing argument 2 of ‘g_hash_table_foreach’ from incompatible pointer type [-Wincompatible-pointer-types] 45 | g_hash_table_foreach (sht, ___lambda4__gh_func, NULL); | ^~~~~~~~~~~~~~~~~~~ | | | void (*)(const void *, const void *, void *) In file included from /usr/include/glib-2.0/glib.h:50, from myhashtable.vala.c:4: /usr/include/glib-2.0/glib/ghash.h:105:61: note: expected ‘GHFunc’ {aka ‘void (*)(void *, void *, void *)’} but argument is of type ‘void (*)(const void *, const void *, void *)’ 105 | GHFunc func, | ~~~~~~~~~~~~~~~~^~~~
运行错误
$ ./myhashtable Segmentation fault
问题分析
- 泛型类型不匹配:
myshowHashTable的参数HashTable sht未指定泛型类型,Vala无法正确识别实际传入的HashTable<string, int>的类型信息,导致生成的C代码中函数指针类型不兼容,触发编译警告。 - 错误的类型转换与格式化:HashTable中存储的value是
int类型,代码中强行将其转为string并使用%s格式化输出,这会导致内存访问越界,直接引发段错误。 - 输出格式缺少换行:printf未添加换行符,会导致输出内容混乱,但不影响程序运行。
解决方法
- 指定泛型参数:将
myshowHashTable的参数改为HashTable<string, int> sht,确保类型匹配,消除编译警告。 - 修正输出格式:针对int类型的value使用
%d格式化,无需强制转换,同时添加换行符优化输出可读性。 - 移除不必要的类型强制转换:key本身就是string类型,无需
(string)key的强制转换。
修正后的完整代码
public static void myshowHashTable(HashTable<string, int> sht){ stdout.printf("Size of sent hashtable: %d\n", (int)sht.size()); sht.foreach((key, val) => { stdout.printf("Key:%s, value:%d\n", key, val); }); } public static void main(string[] args){ HashTable<string,int> ht = new HashTable<string,int>(str_hash, str_equal); ht.insert ("first string", 1); ht.insert ("second string", 2); ht.insert ("third string", 3); myshowHashTable(ht); }
内容的提问来源于stack exchange,提问作者rnso
相关产品推荐
相关产品推荐

