From 5730d6c04258e192195bfbbbed76d68fd78ed458 Mon Sep 17 00:00:00 2001 From: JSDurand Date: Wed, 12 Jan 2022 20:26:08 +0800 Subject: Implement a simple hash table. It is a very basic and simple hash table. It is so simple that I hesitate to call it a hash table. Anyways, I think it suffices for my purposes here. * Makefile.am: Add necessary files. * grammar.c (new_tnt_string): Formatting. * ht.c (new_ht): Constructor (destroy_ht): Destructor (ht_expand): Rehash (ht_insert, ht_delete, ht_find): Main functions. * list.c (add_to_list, list_assure_size): Modify the use of realloc. * test/check_ht.c: Ensure this is working correctly. * util.c (read_entire_file): Modify the use of realloc. --- src/list.c | 43 +++++++++++-------------------------------- 1 file changed, 11 insertions(+), 32 deletions(-) (limited to 'src/list.c') diff --git a/src/list.c b/src/list.c index 3c430f6..db8bc44 100644 --- a/src/list.c +++ b/src/list.c @@ -39,8 +39,7 @@ add_to_list(List *ls, void *element) /* The capacity can be zero only when the list has been destroyed, in which case adding an element to that list is definitely an error. */ - eprintf("%s:%d, Adding an element to a destroyed list.\n", - __FILE__, __LINE__); + fleprintf0("Adding an element to a destroyed list.\n"); } (ls->len)++; @@ -55,30 +54,17 @@ add_to_list(List *ls, void *element) if (new_capacity >= ls->capacity + max_diff) new_capacity = ls->capacity + max_diff; - void **array = MYALLOC(void *, ls->capacity); - - if (array == NULL) { - ls->len -= 1; - return 1; - } - - for (NUM i = 0; i < ls->capacity; i++) - *(array+i) = *(ls->array+i); - /* The new_capacity will not be zero, so upon failure it returns NULL. */ - ls->array = realloc(ls->array, sizeof(void*) * new_capacity); + void **newarr = realloc(ls->array, sizeof(void*) * new_capacity); - if (ls->array == NULL) { + if (newarr == NULL) { + fleprintf0("Fail to realloc\n"); ls->len -= 1; - free(array); return 1; } - for (NUM i = 0; i < ls->capacity; i++) - *(ls->array+i) = *(array+i); - - free(array); + ls->array = newarr; for (NUM i = ls->capacity; i < new_capacity; i++) *(ls->array+i) = NULL; @@ -179,21 +165,14 @@ list_assure_size(List *ls, NUM size) { if (ls->capacity >= size) return 0; /* we are good */ - void **array = MYALLOC(void *, ls->capacity); + void **newarray = realloc(ls->array, sizeof(void*) * size); - if (array == NULL) return 1; - - for (NUM i = 0; i < ls->len; i++) - *(array+i) = *(ls->array+i); - - ls->array = realloc(ls->array, sizeof(void*) * size); - - if (ls->array == NULL) return 1; - - for (NUM i = 0; i < ls->len; i++) - *(ls->array+i) = *(array+i); + if (newarray == NULL) { + fleprintf0("Fail to realloc\n"); + return 1; + } - free(array); + ls->array = newarray; for (NUM i = ls->capacity; i < size; i++) *(ls->array+i) = NULL; -- cgit v1.2.3-18-g5258