From f463655ea5f2a2d861c905574f766970e1045af2 Mon Sep 17 00:00:00 2001 From: Konstantin Kharlamov Date: Fri, 26 Jul 2019 18:02:06 +0300 Subject: [PATCH] darray.h: avoid UB when decrementing zero pointer Sometimes the `&(arr).item[(arr).size]` is a zero pointer. In these cases decrementing this pointer aka `i` results in something like 0xfffffff8. This is UB, and UB sanitizer in particular reports it as ../iscsi/tcmu-runner/libtcmu.c:563:2: runtime error: pointer index expression with base 0x000000000000 overflowed to 0xfffffffffffffff8 In these cases size is `zero` as well, so fix this by simply not running the cycle when the `size` is zero. Signed-off-by: Konstantin Kharlamov --- ccan/darray/darray.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ccan/darray/darray.h b/ccan/darray/darray.h index 58470fdee..451ab4786 100644 --- a/ccan/darray/darray.h +++ b/ccan/darray/darray.h @@ -310,8 +310,8 @@ static inline size_t darray_next_alloc(size_t alloc, size_t need) * * Like darray_foreach, but traverse in reverse order. */ -#define darray_foreach_reverse(i, arr) \ - for ((i) = &(arr).item[(arr).size]; (i)-- > &(arr).item[0]; ) +#define darray_foreach_reverse(ptr, arr) \ + for (size_t _i = 0; _i < (arr).size && ((ptr) = &(arr).item[(arr).size - _i]); ++_i) #endif /* CCAN_DARRAY_H */