Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function makes UThash to fail

I am using the hash-table implementation UThash.

I am inserting elements using the primitive:

    HASH_ADD(hh,hash_table,key,keylen,elem);

And retrieving elements with the primitive:

    HASH_FIND(hh,hash_table,key,keylen,elem);

For some reason I don't know, the behaviour of hash find is being modified when I call a function. That is to say, uthash does not find an element that is present in the table.

I suspect memory has been compromised in some way.

The function that triggers this failure does not need to execute any code to make UThash fail:

    //Note: ct = custom_type
    int func1(ct1 *ptr1, ct2 *ptr2, ct3 *ptr3,char **buffer,size_t *size)
    {
       HASH_FIND(...) //does not work

       /**
        * code
        */
        return 0;
    }

    int func2(ct1 *ptr1,ct2 *ptr2,ct3 *ptr3)
    {
        char *buffer;
        size_t buf_size;

       /**
        * code
        */

        HASH_FIND(...) // works!
        if(func1(ptr1,ptr2,ptr3,&buffer,&buf_size)){
            //code
        }/*error*/

        return 0;
    }

    int func3(ct1 *ptr1,ct2 *ptr2,ct3 *ptr3)
    {
        char *buffer;
        size_t buf_size;

        HASH_FIND(...) // works!
        if(func1(ptr1,ptr2,ptr3,&buffer,&buf_size)){
            //code
        }/*error*/

        /**
         * code
         */

        return 0;
    }

So in both func2() and func3() the same behaviour happens. hash_find() starts to fail after I call func1().

All the rest of the code is executed perfectly and correctly.

My obvious question is what could cause such type of failure?

Thank you for reading and be free to ask any additional info.

like image 794
twawpt Avatar asked Feb 19 '26 16:02

twawpt


1 Answers

This can be caused by adding several items with the same key into hash. If you use uthash, you need to make sure that you don't have duplicated keys in your structure, or to provide a wrapper function which will substitute an old item with the new one. Otherwise, the behaviour of the structure is unpredictable and can cause the failure you described.

From uthash user guide:

If there’s any chance that duplicate keys could be generated by your program, you must explicitly check the uniqueness before adding the key to the hash. If the key is already in the hash, you can simply modify the existing structure in the hash rather than adding the item. It is an error to add two items with the same key to the hash table.

like image 200
Pavel Zaichenkov Avatar answered Feb 22 '26 06:02

Pavel Zaichenkov