I am trying following code of creating and showing a simple HashTable in Vala:
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);
}
Above code compiles with following warnings:
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,
| ~~~~~~~~~~~~~~~~^~~~
When I run the executable created, it give following error:
$ ./myhashtable
Segmentation fault
Where is the problem and how can it be solved?
I don't get about compilation warnings, but segmentation fault is pretty clear: you have HashTable<string,int>, but try to print (string)key, (string)val.
And you omit type specialization at sht argument. Therefore compiler couldn't deduce types.
I got it not crashing this way:
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);
}
);
}