I would like to add pointers to a hash table using hsearch_r. At the moment it does not work using the following code segment (without variable declarations and checks):
// Allocate hash table
htab = calloc( INITIAL_HASH_SIZE, sizeof(struct hsearch_data) );
hcreate_r( INITIAL_HASH_SIZE, htab );
// Add first pointer to hash table
he.key = (char *)&pointer_some_complex_struct1;
if ( hsearch_r( he, FIND, &hep, htab ) == 0) {
he.data = pointer_some_complex_struct1->data;
hsearch_r( he, ENTER, &hep, htab );
}
// Add second pointer to hash table
he.key = (char *)&pointer_some_complex_struct2;
if ( hsearch_r( he, FIND, &hep, htab ) ) {
// CODE ENTERS HERE
}
The second call finds the object regardless it is not present. Any ideas what could be the problem with the above code segment?
The problem is that the keys in hsearch/hsearch_r are NUL-terminated strings, not arbitrary data.