Skip to content

Incorrect double free behavior #181

@ChAoSUnItY

Description

@ChAoSUnItY

Using the code below to initialize buckets for hashmap and frees hashmap:

#include <stdlib.h>

typedef struct hashmap_node {
    char *key;
    void *val;
    struct hashmap_node *next;
} hashmap_node_t;

typedef struct {
    int size;
    hashmap_node_t **buckets;
} hashmap_t;

hashmap_t *hashmap_create(int size)
{
    hashmap_t *map = malloc(sizeof(hashmap_t));
    map->size = size;
    map->buckets = malloc(size * sizeof(hashmap_node_t *));

    for (int i = 0; i < map->size; i++)
        map->buckets[i] = 0;

    return map;
}

void hashmap_free(hashmap_t *map)
{
    for (int i = 0; i < map->size; i++) {
        for (hashmap_node_t *cur = map->buckets[i], *next; cur; cur = next) {
            next = cur->next;
            free(cur->key);
            free(cur->val);
            free(cur);
            cur = next;
        }
    }

    free(map->buckets);
    free(map);
}

int main()
{
    hashmap_t *map = hashmap_create(16);
    map->buckets[0] = malloc(sizeof(hashmap_node_t)); // Simulates put at first bucket
    map->buckets[0]->key = calloc(1, sizeof(char));
    map->buckets[0]->val = malloc(sizeof(int));
    map->buckets[0]->next = NULL;
    hashmap_free(map);
    return 0;
}

Compile with gcc will exit normally, while compile with shecc will cause double free, which is abnormal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions