aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordec05eba <dec05eba@protonmail.com>2020-01-21 02:27:44 +0100
committerdec05eba <dec05eba@protonmail.com>2020-01-21 02:27:44 +0100
commitdea77dd862e71cffb2ebab5079df20e0ebaeddf5 (patch)
treeb90810f39ed5a934ad25bc3a3b541a6a32a3625b
parent5ead0694ba2817057804848fb9b913eb83ef81e8 (diff)
Fix hash map invalid alloc and free on deinit
-rw-r--r--src/std/hash_map.c34
1 files changed, 23 insertions, 11 deletions
diff --git a/src/std/hash_map.c b/src/std/hash_map.c
index 1270514..80fd059 100644
--- a/src/std/hash_map.c
+++ b/src/std/hash_map.c
@@ -4,16 +4,6 @@
#include <stdlib.h>
#include <stdio.h>
-void tsl_hash_map_init(TslHashMap *self) {
- self->buckets_data = NULL;
- self->buckets_size = 0;
- self->buckets_capacity = 0;
-}
-
-void tsl_hash_map_deinit(TslHashMap *self) {
- free(self->buckets_data);
-}
-
typedef struct TslHashMapNode TslHashMapNode;
struct TslHashMapNode {
void *data;
@@ -33,9 +23,31 @@ static void hash_map_node_get(TslHashMapNode *self, uint64_t *hash, TslStringVie
*data = (uint8_t*)self->data + sizeof(uint64_t) + sizeof(key->size) + key->size + sizeof(size_t);
}
+void tsl_hash_map_init(TslHashMap *self) {
+ self->buckets_data = NULL;
+ self->buckets_size = 0;
+ self->buckets_capacity = 0;
+}
+
+void tsl_hash_map_deinit(TslHashMap *self) {
+ TslHashMapNode **bucket = (TslHashMapNode**)self->buckets_data;
+ TslHashMapNode **bucket_end = (TslHashMapNode**)((char*)self->buckets_data + self->buckets_capacity);
+ while(bucket != bucket_end) {
+ TslHashMapNode *node = *bucket;
+ while(node) {
+ TslHashMapNode *prev_node = node;
+ node = node->next;
+ free(prev_node->data);
+ free(prev_node);
+ }
+ ++bucket;
+ }
+ free(self->buckets_data);
+}
+
static int tsl_hash_map_append_bucket(TslHashMapNode **head_node, uint64_t hash, const TslStringView *key, size_t size, const void *data) {
TslHashMapNode *next_node;
- uint8_t *node_data = malloc(sizeof(hash) + sizeof(size) + size);
+ uint8_t *node_data = malloc(sizeof(hash) + sizeof(key->size) + key->size + sizeof(size) + size);
if(!node_data) {
fprintf(stderr, "Error: hash map append failed. Reason: out of memory\n");
return 0;