petewarden / c_hashmap

A simple string hashmap in C
http://petewarden.typepad.com/
Other
524 stars 206 forks source link

Bug when get not exists key #18

Open xiao8385 opened 5 years ago

xiao8385 commented 5 years ago

There is a test program to put key: "key=>6" and get key: "key=>-3"

int main() {
    char key_string[KEY_MAX_LENGTH];
    data_struct_t* value;
    int error;
    map_t map;

    map = hashmap_new();

    snprintf(key_string, KEY_MAX_LENGTH, "key=>%d", 6);
    value = malloc(sizeof(data_struct_t));
    snprintf(value->key_string, KEY_MAX_LENGTH, "value=>%d", 6);
    value->number = 6;

    hashmap_put(map, key_string, value);

    snprintf(key_string, KEY_MAX_LENGTH, "key=>%d", -3);

    error = hashmap_get(map, key_string, (void**) (&value));
    if (error == MAP_MISSING) {
        printf("Missing key:%s\n", key_string);
    } else if (error == MAP_OK) {
        printf("Has key:%s, value.string:%s, value.number:%d\n", key_string, value->key_string, value->number);
    }

    value = malloc(sizeof(data_struct_t));
    snprintf(value->key_string, KEY_MAX_LENGTH, "value=>%d", -3);
    value->number = -3;
    error = hashmap_put(map, key_string, value);
    if (error != MAP_OK) {
        printf("dddddd\n");
    }

    error = hashmap_get(map, key_string, (void**) (&value));
    if (error == MAP_MISSING) {
        printf("Missing key:%s\n", key_string);
    } else if (error == MAP_OK) {
        printf("Has key:%s, value.string:%s, value.number:%d\n", key_string, value->key_string, value->number);
    }
}

Test result as following:

Has key:key=>-3, value.string:value=>6, value.number:6 Has key:key=>-3, value.string:value=>-3, value.number:-3

hashmap123 commented 4 years ago

typedef struct _hashmap_element{ char* key; int in_use; any_t data; } hashmap_element;

char* key key is change

qq1601201705 commented 3 months ago

the project copy the key_string ptr,not deepcopy whole key_string u need to modify src. this project has bugs:1.The map size increase is incorrect;2.You may not be able to find the key when you look for it i will fix it.