saprykin / plibsys

Highly portable C system library: threads and synchronization primitives, sockets (TCP, UDP, SCTP), IPv4 and IPv6, IPC, hash functions (MD5, SHA-1, SHA-2, SHA-3, GOST), binary trees (RB, AVL) and more. Native code performance.
MIT License
672 stars 74 forks source link

Hash table not able to hash string #102

Closed BillyTheSquid21 closed 6 months ago

BillyTheSquid21 commented 6 months ago

When I insert a string into the hash table function, the table registers as having an entry added to it (when checking the length of the values list). However the value cannot be looked up with the p_hash_table_lookup function.

PHashTable* table = NULL;
table = p_hash_table_new();

const char* t = "test";
p_hash_table_insert(table, t, P_INT_TO_POINTER(64));

ppointer val1 = p_hash_table_lookup(table, "test");
ppointer val2 = p_hash_table_lookup(table, t);
printf("%d\n", P_POINTER_TO_INT(val1));
printf("%d\n", P_POINTER_TO_INT(val1));

output:

-1
-1
saprykin commented 6 months ago

You need to consider a few things. First, the way you use it in the first case (to get val1), may work or not, depending on the compiler (just checked on macOS + Clang and it worked). Hash table works with keys and values, but it does not look into the semantics of them, hence, pointers are typically converted to integers. Here, you use the same text string, but there is no guarantee that a compiler will use the same address in both locations.

Second, I guess that you have a typo when you wanted to check val2, and instead you are checking val1 again. This case with val2 should actually work correctly and give you 64 as the result.