From 93be3f7ccaa63b0fd953bcfd88d685b47b76605e Mon Sep 17 00:00:00 2001 From: Ben Harris Date: Sun, 26 Feb 2023 14:24:38 +0000 Subject: Be more careful with type of left operand of << On a 32-bit system, evaluating 1<<31 causes undefined behaviour because 1 is signed and so it produces signed overflow. UBSan has spotted a couple of occasions where this happens in Puzzles, so in each case I've converted the left operand to the unsigned result type we actually want. --- random.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'random.c') diff --git a/random.c b/random.c index 5527d6f..bd11f16 100644 --- a/random.c +++ b/random.c @@ -254,12 +254,12 @@ unsigned long random_bits(random_state *state, int bits) } /* - * `(1 << bits) - 1' is not good enough, since if bits==32 on a + * `(1UL << bits) - 1' is not good enough, since if bits==32 on a * 32-bit machine, behaviour is undefined and Intel has a nasty * habit of shifting left by zero instead. We'll shift by * bits-1 and then separately shift by one. */ - ret &= (1 << (bits-1)) * 2 - 1; + ret &= (1UL << (bits-1)) * 2 - 1; return ret; } -- cgit v1.1