From 8a5405629f7dcbc2504ac55f57775180a011b846 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yaroslav=20de=20la=20Pe=C3=B1a=20Smirnov?= Date: Sun, 7 Nov 2021 00:59:26 +0300 Subject: Fixes and improvements * Fix heap corruption on buffer growth. * Define as static functions that are not used outside a TU. * Other minor changes. --- src/vector.c | 45 +++++++++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 12 deletions(-) (limited to 'src/vector.c') 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 #include "vector.h" +#include +#include + +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); +} -- cgit v1.2.3