为什么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

问题在哪里?如何解决?

我不知道编译警告,但分段错误非常明显:您有HashTable<字符串,int>,但尝试打印(字符串(键,(字符串(值。

并且在sht参数中省略了类型专门化。所以编译器无法推导类型。

我没有这样崩溃:

public static void myshowHashTable(HashTable<string,int> sht){   
stdout.printf("Size of sent hashtable: %dn", (int)sht.size()); 
sht.foreach((key,val) => {
stdout.printf("Key:%s, value:%dn", key, val);
}
); 
}

相关内容

  • 没有找到相关文章

最新更新