From f20792e865f90665bba84c16e94cf4a3aa682a42 Mon Sep 17 00:00:00 2001 From: Tavian Barnes Date: Mon, 18 Jan 2010 23:33:16 -0500 Subject: Add proper range checks to dmnsn_array_insert() and _remove(). --- libdimension/dimension/array.h | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'libdimension') diff --git a/libdimension/dimension/array.h b/libdimension/dimension/array.h index 1b3771d..0a2551b 100644 --- a/libdimension/dimension/array.h +++ b/libdimension/dimension/array.h @@ -147,13 +147,15 @@ dmnsn_array_pop(dmnsn_array *array, void *obj) DMNSN_INLINE void dmnsn_array_insert(dmnsn_array *array, size_t i, const void *obj) { - size_t size = dmnsn_array_size(array); - /* Increase the size by 1 */ - dmnsn_array_resize(array, size + 1); + size_t size = dmnsn_array_size(array) + 1; + if (i >= size) + size = i + 1; + dmnsn_array_resize(array, size); + /* Move the elements at and after `i' 1 to the right */ memmove((char *)array->ptr + array->obj_size*(i + 1), (char *)array->ptr + array->obj_size*i, - array->obj_size*(size - i)); + array->obj_size*(size - i - 1)); /* Insert `obj' at `i' */ memcpy((char *)array->ptr + array->obj_size*i, obj, array->obj_size); } @@ -163,6 +165,11 @@ DMNSN_INLINE void dmnsn_array_remove(dmnsn_array *array, size_t i) { size_t size = dmnsn_array_size(array); + if (i >= size) { + /* Range check failed */ + dmnsn_error(DMNSN_SEVERITY_HIGH, "Array index out of bounds."); + } + /* Move the array elements after `i' 1 to the left */ memmove((char *)array->ptr + array->obj_size*i, (char *)array->ptr + array->obj_size*(i + 1), -- cgit v1.2.3