diff options
author | Yaroslav de la Peña Smirnov <yps@yaroslavps.com> | 2021-11-07 00:59:26 +0300 |
---|---|---|
committer | Yaroslav de la Peña Smirnov <yps@yaroslavps.com> | 2021-11-07 00:59:26 +0300 |
commit | 8a5405629f7dcbc2504ac55f57775180a011b846 (patch) | |
tree | d5009f3bce187a92386148b633b59787d6499244 /src/vector.c | |
parent | 33bdfde2be7e1c568d5e12ad1b27b7023dbd1b1b (diff) | |
download | unja-8a5405629f7dcbc2504ac55f57775180a011b846.tar.gz unja-8a5405629f7dcbc2504ac55f57775180a011b846.zip |
Fixes and improvements
* Fix heap corruption on buffer growth.
* Define as static functions that are not used outside a TU.
* Other minor changes.
Diffstat (limited to 'src/vector.c')
-rw-r--r-- | src/vector.c | 45 |
1 files changed, 33 insertions, 12 deletions
diff --git a/src/vector.c b/src/vector.c index 46a65e5..536fd33 100644 --- a/src/vector.c +++ b/src/vector.c @@ -1,23 +1,44 @@ -#include <stdlib.h> #include "vector.h" +#include <stdlib.h> +#include <stdbool.h> + +static bool +vector_grow(struct vector *vec) +{ + vec->cap *= VECTOR_GROW_RATE; + vec->values = realloc(vec->values, sizeof(*vec->values) * vec->cap); + if (vec->values == NULL) { + return false; + } + + return true; +} + /* create a new vector of the given capacity */ -struct vector* vector_new(int cap) { - struct vector *l = malloc(sizeof *l); - l->size = 0; - l->cap = cap; - l->values = malloc(l->cap * sizeof *l->values); - return l; +struct vector * +vector_new(size_t cap) +{ + struct vector *vec = malloc(sizeof *vec); + vec->size = 0; + vec->cap = cap; + vec->values = malloc(vec->cap * sizeof *vec->values); + return vec; } /* push a new value to the end of the vector's memory */ -int vector_push(struct vector *vec, void *value) { +size_t +vector_push(struct vector *vec, void *value) +{ + if (vec->size == vec->cap) vector_grow(vec); vec->values[vec->size++] = value; return vec->size - 1; } /* free vector related memory */ -void vector_free(struct vector *l) { - free(l->values); - free(l); -}
\ No newline at end of file +void +vector_free(struct vector *vec) +{ + free(vec->values); + free(vec); +} |