Commit df8c663a authored by Damien Grassart's avatar Damien Grassart Committed by David Gibson

darray: Fix bug in the darray_remove() macro

The memmove() call should be using the index argument to determine the
number of bytes to copy. To be consistent with the rest of the code,
we should also not evaluate the index parameter multiple
times. Calling this with rand() % arr.size would otherwise generally
segfault.

Finally, we want to avoid using "index" as an identifier so as to not
shadow index(3) in the C library.
Signed-off-by: default avatarDamien Grassart <damien@grassart.com>
Signed-off-by: default avatarDavid Gibson <david@gibson.dropbear.id.au>
parent d4779b16
...@@ -170,8 +170,8 @@ typedef darray(unsigned long) darray_ulong; ...@@ -170,8 +170,8 @@ typedef darray(unsigned long) darray_ulong;
memmove((arr).item+1, (arr).item, ((arr).size-1)*sizeof(*(arr).item)); \ memmove((arr).item+1, (arr).item, ((arr).size-1)*sizeof(*(arr).item)); \
(arr).item[0] = (__VA_ARGS__); \ (arr).item[0] = (__VA_ARGS__); \
} while(0) } while(0)
#define darray_insert(arr, index, ...) do { \ #define darray_insert(arr, i, ...) do { \
size_t index_ = index; \ size_t index_ = (i); \
darray_resize(arr, (arr).size+1); \ darray_resize(arr, (arr).size+1); \
memmove((arr).item+index_+1, (arr).item+index_, ((arr).size-index_-1)*sizeof(*(arr).item)); \ memmove((arr).item+index_+1, (arr).item+index_, ((arr).size-index_-1)*sizeof(*(arr).item)); \
(arr).item[index_] = (__VA_ARGS__); \ (arr).item[index_] = (__VA_ARGS__); \
...@@ -230,9 +230,10 @@ typedef darray(unsigned long) darray_ulong; ...@@ -230,9 +230,10 @@ typedef darray(unsigned long) darray_ulong;
#define darray_pop(arr) ((arr).item[--(arr).size]) #define darray_pop(arr) ((arr).item[--(arr).size])
#define darray_pop_check(arr) ((arr).size ? darray_pop(arr) : NULL) #define darray_pop_check(arr) ((arr).size ? darray_pop(arr) : NULL)
/* Warning, slow: Requires copying all elements after removed item. */ /* Warning, slow: Requires copying all elements after removed item. */
#define darray_remove(arr, index) do { \ #define darray_remove(arr, i) do { \
if (index < arr.size-1) \ size_t index_ = (i); \
memmove(&(arr).item[index], &(arr).item[index+1], ((arr).size-1-i)*sizeof(*(arr).item)); \ if (index_ < arr.size-1) \
memmove(&(arr).item[index_], &(arr).item[index_+1], ((arr).size-1-index_)*sizeof(*(arr).item)); \
(arr).size--; \ (arr).size--; \
} while(0) } while(0)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment