Skip to content

Weird memory issue (undefined behavior) on macOS compiled with clang #32

@dmitry-kabanov

Description

@dmitry-kabanov

Hi,

I use hashmap in my project. In Linux everything works.
I try to make my code work on macOS and I run into some strange behavior: code basically segfaults immediately.
After running with -fsanitize=undefined, I have managed to find a potential reason for this:

/Users/dima/Developer/tmp/open-interfaces-update-2025-09-nr-3/build.debug_verbose_info_and_sanitize/_deps/hashmap-src/src/hashmap.c:188:47: runtime error: applying zero offset to null pointer
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /Users/dima/Developer/tmp/open-interfaces-update-2025-09-nr-3/build.debug_verbose_info_and_sanitize/_deps/hashmap-src/src/hashmap.c:188:47

which is about this code:

static int hashmap_rehash(struct hashmap_base *hb, size_t table_size)
{
    size_t old_size;
    struct hashmap_entry *old_table;
    struct hashmap_entry *new_table;
    struct hashmap_entry *entry;
    struct hashmap_entry *new_entry;

    assert((table_size & (table_size - 1)) == 0);
    assert(table_size >= hb->size);

    new_table = (struct hashmap_entry *)calloc(table_size, sizeof(struct hashmap_entry));
    if (!new_table) {
        return -ENOMEM;
    }
    old_size = hb->table_size;
    old_table = hb->table;
    assert(old_table != NULL);
    hb->table_size = table_size;
    hb->table = new_table;

    /* Rehash */
    for (entry = old_table; entry < old_table + old_size; ++entry) {
        if (!entry->key) {
            continue;
        }
        new_entry = hashmap_entry_find(hb, entry->key, true);
        /* Failure indicates an algorithm bug */
        assert(new_entry != NULL);

        /* Shallow copy */
        *new_entry = *entry;
    }
    free(old_table);
    return 0;
}

The assertin the middle is added by me; the problem (line 188, column 47) is in the end condition of the for loop (old_table + old_size). And actually the assert assert(old_table != NULL) fails, that is, for some reason old_table is NULL.

Could you please help me find out what can be the problem? Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions