attractivechaos / khashl

Generic hash table library in C
21 stars 0 forks source link

Memory allocation issues #5

Open JacksonAllan opened 4 months ago

JacksonAllan commented 4 months ago

There seems to be a few issues revolving around memory allocation.

In _resize:

        new_used = (khint32_t*)kmalloc(__kh_fsize(new_n_buckets) * sizeof(khint32_t)); \
        memset(new_used, 0, __kh_fsize(new_n_buckets) * sizeof(khint32_t)); \
        if (!new_used) return -1; /* not enough memory */ \

Here, the memory is written to via memset before the check to ensure that the allocation succeeded. The second and third line should be switched, I think.

In _resize:

        if (n_buckets > new_n_buckets) /* shrink the hash table */ \
            h->keys = (khkey_t*)krealloc((void *)h->keys, new_n_buckets * sizeof(khkey_t)); \

Here, the pointer returned by krealloc is never checked (and if it's NULL, the original memory is also leaked).

And in _init for the ensemble struct:

        HType *g; \
        g = (HType*)kcalloc(1, sizeof(*g)); \
        g->bits = bits; \
        g->sub = (HType##_sub*)kcalloc(1U<<bits, sizeof(*g->sub)); \
        return g; \

Here, the memory for g is being written to without any check to make sure that the allocation succeeded. g->sub is also never checked.