From deeb6aa4aa60e22190087a9615447e742c84a19c Mon Sep 17 00:00:00 2001 From: Kai Stevenson Date: Thu, 16 Feb 2023 19:24:20 -0800 Subject: added scoping and a lot of memory leaks --- src/hashtable.c | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) (limited to 'src/hashtable.c') diff --git a/src/hashtable.c b/src/hashtable.c index 7cb253c..2f4ca64 100644 --- a/src/hashtable.c +++ b/src/hashtable.c @@ -5,18 +5,23 @@ const unsigned int fnvPrime = 16777619; const unsigned int fnvOffset = 2166136261U; -pair_t* init_pair(char* key, void* value) { - pair_t* p = malloc(sizeof(pair_t)); - p->key = key; - p->value = value; +pair_t init_pair(char* key, void* value) { + pair_t p; + p.key = key; + p.value = value; return p; } -hashtable_t* init_hashtable(unsigned int capacity) { +hashtable_t* init_hashtable(unsigned int capacity, hashtable_t* parent) { hashtable_t* ht = malloc(sizeof(hashtable_t)); - ht->pairs = calloc(capacity, sizeof(pair_t*)); + ht->pairs = calloc(capacity, sizeof(pair_t)); ht->capacity = capacity; + ht->parent = parent; return ht; } +void destroy_hashtable(hashtable_t* hashtable) { + free(hashtable->pairs); + free(hashtable); +} //FNV-1a hash unsigned int get_hash(char* str) { unsigned int hash = fnvOffset; @@ -28,12 +33,22 @@ unsigned int get_hash(char* str) { } /* TODO: handle collision TODO: return 0 if something goes wrong */ -unsigned int hashtable_add_pair(hashtable_t* hashtable, pair_t* pair) { - unsigned int hash = get_hash(pair->key); +unsigned int hashtable_add_pair(hashtable_t* hashtable, pair_t pair) { + unsigned int hash = get_hash(pair.key); hashtable->pairs[hash % hashtable->capacity] = pair; return hash; } -pair_t* hashtable_get_pair(hashtable_t* hashtable, char* key) { +pair_t hashtable_get_pair(hashtable_t* hashtable, char* key) { unsigned int hash = get_hash(key); return hashtable->pairs[hash % hashtable->capacity]; } +pair_t hashtable_get_pair_recurse(hashtable_t* origin, char* key) { + pair_t pair = hashtable_get_pair(origin, key); + if (pair.key != NULL) { + return pair; + } + if (origin->parent != NULL) { + return hashtable_get_pair_recurse(origin->parent, key); + } + return pair; +} -- cgit v1.3.1