From d246077e78bb1aeafe8829927db23f281cd03c72 Mon Sep 17 00:00:00 2001 From: Ben Harris Date: Mon, 2 Jan 2023 16:48:20 +0000 Subject: Add a macro of an upper bound on the formatted length of an integer There are lots of places where Puzzles formats integers into fixed-length buffers using sprintf() with a "%d" format. This isn't very safe, since C doesn't guarantee any particular maximum size for an "int". However, the restrictions on representations of integers means we can infer an upper bound using sizeof(), CHAR_BIT, and an approximation to the binary log of 10. --- puzzles.h | 3 +++ 1 file changed, 3 insertions(+) (limited to 'puzzles.h') diff --git a/puzzles.h b/puzzles.h index cbe7f88..2f49613 100644 --- a/puzzles.h +++ b/puzzles.h @@ -18,6 +18,9 @@ #define STR_INT(x) #x #define STR(x) STR_INT(x) +/* An upper bound on the length of sprintf'ed integers (signed or unsigned). */ +#define MAX_DIGITS(x) (sizeof(x) * CHAR_BIT / 3 + 2) + /* NB not perfect because they evaluate arguments multiple times. */ #ifndef max #define max(x,y) ( (x)>(y) ? (x) : (y) ) -- cgit v1.1