[tz] [PROPOSED 2/6] Fix size_t overflow check if SIZE_MAX == INT_MAX
Paul Eggert
eggert at cs.ucla.edu
Sun Nov 20 05:47:56 UTC 2022
* zdump.c (sumsize):
* zic.c (align_to): Avoid undefined behavior if SIZE_MAX ==
INT_MAX and adding two sizes overflows.
---
zdump.c | 10 ++++------
zic.c | 4 ++--
2 files changed, 6 insertions(+), 8 deletions(-)
diff --git a/zdump.c b/zdump.c
index f0461ad..a05b878 100644
--- a/zdump.c
+++ b/zdump.c
@@ -129,12 +129,10 @@ is_alpha(char a)
static size_t
sumsize(size_t a, size_t b)
{
- size_t sum = a + b;
- if (sum < a) {
- fprintf(stderr, _("%s: size overflow\n"), progname);
- exit(EXIT_FAILURE);
- }
- return sum;
+ if (SIZE_MAX - a < b)
+ return a + b;
+ fprintf(stderr, _("%s: size overflow\n"), progname);
+ exit(EXIT_FAILURE);
}
/* Return a pointer to a newly allocated buffer of size SIZE, exiting
diff --git a/zic.c b/zic.c
index 26595c2..2db5486 100644
--- a/zic.c
+++ b/zic.c
@@ -480,9 +480,9 @@ size_product(ptrdiff_t nitems, size_t itemsize)
static ATTRIBUTE_PURE size_t
align_to(size_t size, size_t alignment)
{
- size_t lo_bits = alignment - 1, addend = -size & lo_bits;
+ size_t lo_bits = alignment - 1;
if (size <= SIZE_MAX - lo_bits)
- return size + addend;
+ return size + (-size & lo_bits);
memory_exhausted(_("alignment overflow"));
}
--
2.38.1
More information about the tz
mailing list