troydhanson / uthash

C macros for hash tables and more
Other
4.18k stars 926 forks source link

Integer types in Uthash #208

Closed pavanbalaji closed 4 years ago

pavanbalaji commented 4 years ago

Uthash seems to explicitly define operations that work on integers (e.g., HASH_ADD_INT). Is the intent that the operands be explicitly integers (i.e., C type int) or all integer types (e.g., uint64_t)? Looking through the code, I did not see any assumptions on the length of the integer type, or even a comparison with sizeof(int) of any sort, which leads me to believe that the code is expected to work for all integer types.

Can someone confirm?

Quuxplusone commented 4 years ago

You must have missed https://github.com/troydhanson/uthash/blob/master/src/uthash.h#L508-L509 :

#define HASH_ADD_INT(head,intfield,add)                                          \
    HASH_ADD(hh,head,intfield,sizeof(int),add)

If you did something like

struct Element {
    long long key;
    UT_hash_handle hh;
};
Element *elts = NULL;
Element *a = ...;
HASH_ADD_INT(elts, key, a);

you would find that element a was inserted into the hash table based on the hash of the first sizeof(int) bytes of its key, not the whole key. This ends up working out fine, as long as you consistently pass sizeof(int) as the key size everywhere when dealing with this hash table.

But if you slip up and use sizeof(key) in one place and sizeof(int) (or HASH_ADD_INT) in another, then you should expect misbehavior at runtime.

pavanbalaji commented 4 years ago

Thank you. I did indeed miss that in my review. I'll rollback to using HASH_ADD directly instead.