nooc

Unnamed repository; edit this file 'description' to name the repository.
git clone git://git.nihaljere.xyz/nooc
Log | Files | Refs | LICENSE

commit 8f09fd143fdab8b36157816c13f9f7ec658758c0
parent ef56b9d99377d6a8d10e2e687759aac2a9993032
Author: Nihal Jere <nihal@nihaljere.xyz>
Date:   Sat,  6 Nov 2021 20:40:25 -0500

array: fix allocation

Previously, if an allocation was done for count element and a another
push was made for over count elements, it wouldn't allocate enough
memory. This is because we assumed that we're only pushing one element
at a time, which is no longer true.

Diffstat:
Marray.c | 11++++++++---
1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/array.c b/array.c @@ -1,15 +1,20 @@ +#include <stdbool.h> #include <stddef.h> #include <stdlib.h> #include <string.h> -#include <stdio.h> #include "array.h" int _array_add(void **data, size_t size, size_t count, size_t *len, size_t *cap, void *new) { - if (*len == *cap) { - *cap = *cap ? 2*(*cap)*size : count; + bool need_realloc; + while (*cap < *len + count) { + need_realloc = true; + *cap = *cap ? *cap * 2 : 1; + } + + if (need_realloc) { *data = realloc(*data, size*(*cap)); if (*data == NULL) return -1;