chiark / gitweb /
Fix build failure reported in gcc 9.
authorSimon Tatham <anakin@pobox.com>
Sun, 1 Sep 2019 21:26:22 +0000 (22:26 +0100)
committerSimon Tatham <anakin@pobox.com>
Sun, 1 Sep 2019 21:26:22 +0000 (22:26 +0100)
Apparently gcc 9 is clever enough to say 'Hey, runtime field width in
an sprintf targeting a fixed-size buffer!', but not clever enough to
notice that the width was computed earlier as the max of lots of
default-width sprintfs into the same buffer (so _either_ it's safe, or
else - on a hypothetical platform with a 263-bit int - the damage was
already done).

Added a bounds check or two to keep it happy.

twiddle.c

index 06f6ff1114bf0805773fb5ad3276340ea3cafda2..07e2f81d58ed23bcb4d923cbfeed3afd1d6a16df 100644 (file)
--- a/twiddle.c
+++ b/twiddle.c
@@ -550,6 +550,12 @@ static char *game_text_format(const game_state *state)
     int i, x, y, col, maxlen;
     bool o = state->orientable;
 
+    /* Pedantic check: ensure buf is large enough to format an int in
+     * decimal, using the bound log10(2) < 1/3. (Obviously in practice
+     * int is not going to be larger than even 32 bits any time soon,
+     * but.) */
+    assert(sizeof(buf) >= 1 + sizeof(int) * CHAR_BIT/3);
+
     /*
      * First work out how many characters we need to display each
      * number. We're pretty flexible on grid contents here, so we
@@ -561,6 +567,11 @@ static char *game_text_format(const game_state *state)
        if (col < x) col = x;
     }
 
+    /* Reassure sprintf-checking compilers like gcc that the field
+     * width we've just computed is not now excessive */
+    if (col >= sizeof(buf))
+        col = sizeof(buf)-1;
+
     /*
      * Now we know the exact total size of the grid we're going to
      * produce: it's got h rows, each containing w lots of col+o,