From 2416c2e46680a10ca45f11ecee4fbbf7a4501256 Mon Sep 17 00:00:00 2001 From: Patrick Pelissier Date: Wed, 5 Dec 2018 17:52:02 +0100 Subject: [PATCH] Fix bug of overflow of 'alloc-num' if alloc < num (case where the service is called with a big number to insert --- m-array.h | 13 ++++++++++--- tests/test-marray.c | 10 +++++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/m-array.h b/m-array.h index d4023de3..e8c8477d 100644 --- a/m-array.h +++ b/m-array.h @@ -496,10 +496,17 @@ ARRAYI_CONTRACT(v); \ assert(i <= v->size); \ size_t size = v->size + num; \ - /* Avoid overflow of v->size + num */ \ - if (v->size > v->alloc-num) { \ + /* Test for overflow of variable size */ \ + if (M_UNLIKELY (size <= v->size)) { \ + /* Unlikely case of nothing to do */ \ + if (num == 0) return; \ + M_MEMORY_FULL(sizeof (type) * v->size); \ + return ; \ + } \ + /* Test if alloc array is sufficient */ \ + if (size > v->alloc) { \ size_t alloc = M_CALL_INC_ALLOC(oplist, size) ; \ - if (M_UNLIKELY (size <= v->size || alloc <= v->alloc)) { \ + if (M_UNLIKELY (alloc <= v->alloc)) { \ M_MEMORY_FULL(sizeof (type) * alloc); \ return ; \ } \ diff --git a/tests/test-marray.c b/tests/test-marray.c index 645766ce..9fec2fc0 100644 --- a/tests/test-marray.c +++ b/tests/test-marray.c @@ -128,7 +128,15 @@ static void test_uint(void) assert(*array_uint_cget(v2, 500) == 0); assert(array_uint_size(v2) == 1005); assert(*array_uint_cget(v2, 1004) == 0); - + array_uint_set_at(v2, 1004, 465487); + array_uint_insert_v (v2, 500, 0); + assert(array_uint_size(v2) == 1005); + assert(*array_uint_cget(v2, 1004) == 465487); + array_uint_insert_v (v2, 1004, 10000); + assert(array_uint_size(v2) == 11005); + assert(*array_uint_cget(v2, 11004) == 465487); + array_uint_resize(v2, 1005); + array_uint_init(v); array_uint_swap(v,v2); assert(array_uint_size(v) == 1005);