From dd279150dca790876e4531521c389f795561e39c Mon Sep 17 00:00:00 2001 From: =?utf8?q?Niels=20M=C3=B6ller?= Date: Fri, 13 Jul 2018 19:38:59 +0200 Subject: [PATCH] Check for allocation overflow in eratosthenes program. --- ChangeLog | 6 ++++++ examples/eratosthenes.c | 9 +++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index 23a0331a..1d318208 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +2018-07-13 Niels Möller + + * examples/eratosthenes.c (vector_alloc): Add assert related to + overflow in the size calculation. Fixes a corner case identified + by static analysis. + 2018-07-12 Niels Möller * examples/eratosthenes.c (main): Don't allocate bitmap storage diff --git a/examples/eratosthenes.c b/examples/eratosthenes.c index 71161820..35f84e1c 100644 --- a/examples/eratosthenes.c +++ b/examples/eratosthenes.c @@ -92,8 +92,13 @@ isqrt(unsigned long n) static unsigned long * vector_alloc(unsigned long size) { - unsigned long end = (size + BITS_PER_LONG - 1) / BITS_PER_LONG; - unsigned long *vector = malloc (end * sizeof(*vector)); + unsigned long end; + unsigned long *vector; + + assert (size <= ULONG_MAX - (BITS_PER_LONG - 1)); + + end = (size + BITS_PER_LONG - 1) / BITS_PER_LONG; + vector = malloc (end * sizeof(*vector)); if (!vector) { -- 2.47.2