diff options
author | Nikias Bassen | 2019-06-12 21:15:08 +0200 |
---|---|---|
committer | Nikias Bassen | 2019-06-12 21:15:08 +0200 |
commit | 2501f51e0fe2fad17ce4966542138d3f32dd533c (patch) | |
tree | 774ea671ae3d1aa79f44c0328573283a104cad1c /common | |
parent | 60109fdef47dfe0badfb558a6a2105e8fb23660a (diff) | |
download | libusbmuxd-2501f51e0fe2fad17ce4966542138d3f32dd533c.tar.gz libusbmuxd-2501f51e0fe2fad17ce4966542138d3f32dd533c.tar.bz2 |
common: Use portable pointer initialization and assert on allocation failure
Diffstat (limited to 'common')
-rw-r--r-- | common/collection.c | 22 |
1 files changed, 16 insertions, 6 deletions
diff --git a/common/collection.c b/common/collection.c index d120b3e..92bd645 100644 --- a/common/collection.c +++ b/common/collection.c @@ -28,11 +28,19 @@ #include <stdio.h> #include "collection.h" +#undef NDEBUG // we need to make sure we still get assertions because we can't handle memory allocation errors +#include <assert.h> + +#define INIT_NULL(addr, count) { unsigned int i_ = 0; for (i_ = 0; i_ < count; i_++) ((void**)addr)[i_] = NULL; } + +#define CAPACITY_STEP 8 + void collection_init(struct collection *col) { - col->list = malloc(sizeof(void *)); - memset(col->list, 0, sizeof(void *)); - col->capacity = 1; + col->list = malloc(sizeof(void *) * CAPACITY_STEP); + assert(col->list); + INIT_NULL(col->list, CAPACITY_STEP); + col->capacity = CAPACITY_STEP; } void collection_free(struct collection *col) @@ -51,10 +59,12 @@ void collection_add(struct collection *col, void *element) return; } } - col->list = realloc(col->list, sizeof(void*) * col->capacity * 2); - memset(&col->list[col->capacity], 0, sizeof(void *) * col->capacity); + void **newlist = realloc(col->list, sizeof(void*) * (col->capacity + CAPACITY_STEP)); + assert(newlist); + col->list = newlist; + INIT_NULL(&col->list[col->capacity], CAPACITY_STEP); col->list[col->capacity] = element; - col->capacity *= 2; + col->capacity += CAPACITY_STEP; } int collection_remove(struct collection *col, void *element) |