From 9bcc0e94b891221b9537a8e9faac080ca6b78e95 Mon Sep 17 00:00:00 2001 From: Mansour Moufid Date: Thu, 22 Sep 2011 12:05:42 -0400 Subject: [PATCH] Add a new `xsumn' function to `lib/xsize.h'. This implements a variadic sum function with overflow checking, similar to xsum{2,3,4} but for an arbitrary n number of arguments. For example: size_t size = xsumn (4, 9, 10, 11, 12); /* size == 42 */ void *p = (size_in_bounds_p (size) ? malloc (size) : NULL); --- lib/xsize.h | 20 ++++++++++++++++++++ 1 files changed, 20 insertions(+), 0 deletions(-) diff --git a/lib/xsize.h b/lib/xsize.h index f75655a..af2fd2d 100644 --- a/lib/xsize.h +++ b/lib/xsize.h @@ -28,6 +28,8 @@ # include #endif +#include + /* The size of memory objects is often computed through expressions of type size_t. Example: void* p = malloc (header_size + n * element_size). @@ -79,6 +81,24 @@ xsum4 (size_t size1, size_t size2, size_t size3, size_t size4) return xsum (xsum (xsum (size1, size2), size3), size4); } +/* Sum of n sizes, with overflow check. */ +static inline size_t +xsumn (size_t n, ...) +{ + va_list ap; + size_t i, x, sum = 0; + + va_start (ap, n); + for (i = 0; i < n; i++) + { + x = va_arg (ap, size_t); + sum = xsum (sum, x); + } + va_end (ap); + + return sum; +} + /* Maximum of two sizes, with overflow check. */ static inline size_t #if __GNUC__ >= 3 -- 1.7.1