num2str(): Fix overflow handling
authorBart Van Assche <bvanassche@acm.org>
Thu, 2 Jul 2020 21:53:09 +0000 (14:53 -0700)
committerBart Van Assche <bvanassche@acm.org>
Thu, 2 Jul 2020 22:27:39 +0000 (15:27 -0700)
This patch changes the output for the arguments (UINT64_MAX, 4, 1, 0,
N2S_NONE, "18.4") from "18.4(null)" into "18.4".

This patch fixes the following Coverity complaint:

CID 169307 (#1 of 1): Out-of-bounds read (OVERRUN)
27. overrun-local: Overrunning array of 6 8-byte elements at element
    index 6 (byte offset 55) by dereferencing pointer unitprefix + post_index.

Signed-off-by: Bart Van Assche <bvanassche@acm.org>
lib/num2str.c

index 923e21d9ce9abc321aa1fb07c67ee9506b174383..7f628d29a05121167f147de03700524e67205c31 100644 (file)
@@ -80,14 +80,14 @@ char *num2str(uint64_t num, int maxlen, int base, int pow2, enum n2s_unit units)
                post_index++;
        }
 
+       if (post_index >= ARRAY_SIZE(sistr))
+               post_index = 0;
+
        /*
         * If no modulo, then we're done.
         */
        if (modulo == -1U) {
 done:
-               if (post_index >= ARRAY_SIZE(sistr))
-                       post_index = 0;
-
                if (asprintf(&buf, "%llu%s%s", (unsigned long long) num,
                             unitprefix[post_index], unitstr[units]) < 0)
                        buf = NULL;