From 21806e77a79723ff95f1941a57180b118c12120b Mon Sep 17 00:00:00 2001 From: Francesco Date: Mon, 16 Mar 2026 23:11:15 +0100 Subject: [PATCH] refactor(test): improve hashmap test --- hashmap/myhashmap.h | 2 ++ test/hashmap/hm1.c | 10 ++++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/hashmap/myhashmap.h b/hashmap/myhashmap.h index 919ccb1..7da7b99 100644 --- a/hashmap/myhashmap.h +++ b/hashmap/myhashmap.h @@ -100,6 +100,8 @@ void hm_free_bucket(bucket_s *bucket); * If the key already exists, the old value is freed (if free_value_fn is provided) * and replaced with the new value. If the key doesn't exist, a new entry is created. * Both key and value are copied into the hashmap using memcpy. + * The caller must pass buffers that are readable for at least key_size/value_size bytes. + * For C-string keys, use a fixed-size key buffer (or set key_size to the exact copied size). * * @param[in] hashmap Pointer to the hash map. * @param[in] key Pointer to the key to insert (will be copied, must not be NULL). diff --git a/test/hashmap/hm1.c b/test/hashmap/hm1.c index 8d50d1e..cd4a664 100644 --- a/test/hashmap/hm1.c +++ b/test/hashmap/hm1.c @@ -53,7 +53,7 @@ void test_hm1(void) { /* Pass your custom hash, equal and free functions */ /* This hashmap will contain names as keys and a custom type as value */ size_t key_size = sizeof(char) * MAX_STR_LEN; - size_t value_size = sizeof(int) + sizeof(char) * MAX_STR_LEN; + size_t value_size = sizeof(struct my_custom_type); hashmap_s *map = hm_new(my_hash_func, my_equal_fun, my_free_key, my_free_value, key_size, value_size); assert(map != NULL); @@ -65,11 +65,13 @@ void test_hm1(void) { strncpy(p1.favourite_brand, "Ferrari", sizeof(p1.favourite_brand)); /* Insert a new pair */ - assert(hm_set(map, "John", &p1)); + char john_key[MAX_STR_LEN] = {0}; + strncpy(john_key, "John", sizeof(john_key) - 1); + assert(hm_set(map, john_key, &p1)); /* Retrieve the data */ /* Remember to free the value from the get function */ - bucket_s *john = hm_get(map, "John"); + bucket_s *john = hm_get(map, john_key); assert(john != NULL); char *name = (char *)john->key; @@ -85,7 +87,7 @@ void test_hm1(void) { hm_free_bucket(john); /* Remove a key from hash map */ - assert(hm_remove(map, "John")); + assert(hm_remove(map, john_key)); /* Deallocate */ hm_free(map);