From 42c936a1884d40b6679ba9f7f80bf308c5fb1f7f Mon Sep 17 00:00:00 2001 From: Mark Wooding Date: Fri, 8 Apr 2022 15:29:13 +0100 Subject: [PATCH] lib.[ch]: Move the memory allocation out-of-line. --- lib.c | 13 +++++++++++++ lib.h | 16 +++++++++------- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/lib.c b/lib.c index 7021661..25cc829 100644 --- a/lib.c +++ b/lib.c @@ -98,6 +98,19 @@ long parse_int(const char **p_inout, unsigned f, return (x); } +/*----- Resizing arrays ---------------------------------------------------*/ + +void *vec__grow(void *p, size_t esz, size_t *sz_inout) +{ + size_t sz = *sz_inout, want; + + sz = sz ? 2*sz : 32; + want = sz*esz; + p = realloc(p, want); + if (!p) bail("out of memory allocating %zu bytes", want); + *sz_inout = sz; return (p); +} + /*----- System utilities --------------------------------------------------*/ void sit(double t) diff --git a/lib.h b/lib.h index 553a5fe..2b127e3 100644 --- a/lib.h +++ b/lib.h @@ -160,14 +160,16 @@ extern PRINTF_LIKE(2, 3) NORETURN } while (0) /* Free the vector VV. It's safe to free a vector multiple times. */ +extern void *vec__grow(void *p, size_t esz, size_t *sz_inout); + /* Extend the buffer P, which currently has space for *SZ_INOUT + * elements, each ESZ bytes in size, so that there's space for at + * least one one more; return the new buffer address, and update + * *SZ_INOUT with the new size. + */ + #define VEC_PUSH(p, vv) do { \ - size_t _want; \ - if ((vv)->n >= (vv)->sz) { \ - (vv)->sz = (vv)->sz ? 2*(vv)->sz : 32; \ - _want = (vv)->sz*sizeof(*(vv)->v); \ - (vv)->v = realloc((vv)->v, _want); \ - if (!(vv)->v) bail("out of memory allocating %zu bytes", _want); \ - } \ + if ((vv)->n >= (vv)->sz) \ + (vv)->v = vec__grow((vv)->v, sizeof(*(vv)->v), &(vv)->sz); \ (p) = &(vv)->v[(vv)->n++]; \ } while (0) /* Add an initialized element to the end of vector VV, storing its -- 2.11.0