Fix num2str() output when maxlen <= strlen(tmp)
authorTomohiro Kusumi <tkusumi@tuxera.com>
Tue, 4 Apr 2017 20:22:17 +0000 (23:22 +0300)
committerJens Axboe <axboe@fb.com>
Sat, 8 Apr 2017 17:04:21 +0000 (11:04 -0600)
Since a local variable decimals is unsigned int, this conditional
 if (decimals <= 1)
needs cast as shown below.
 if ((int)decimals <= 1)

Otherwise it results in showing some garbage in case of maxlen == 0,

 # cat ./test0.c
 #include <stdio.h>
 #include "lib/num2str.h"
 int main(void) {
         printf("%s\n", num2str(123, 3, 1, 1, N2S_BYTE));
         printf("%s\n", num2str(123, 2, 1, 1, N2S_BYTE));
         printf("%s\n", num2str(123, 1, 1, 1, N2S_BYTE));
         printf("%s\n", num2str(123, 0, 1, 1, N2S_BYTE));
         return 0;
 }
 # gcc -Wall -g -DCONFIG_STATIC_ASSERT ./test0.c ./lib/num2str.c
 # ./a.out
 123B
 0KiB
 0KiB
 0.0?$-JB
 # ./a.out
 123B
 0KiB
 0KiB
 0.0#;bB
 # ./a.out
 123B
 0KiB
 0KiB
 0.0|B

whereas with this commit it prints "0B".

 # gcc -Wall -g -DCONFIG_STATIC_ASSERT ./test0.c ./lib/num2str.c
 # ./a.out
 123B
 0KiB
 0KiB
 0B

Signed-off-by: Tomohiro Kusumi <tkusumi@tuxera.com>
Signed-off-by: Jens Axboe <axboe@fb.com>
lib/num2str.c

index 2f714ccd69ffc6040d1d3c80c0e212b5279298d5..448d3ff88b00cbe41c3fcbeb21665d19496cf2f7 100644 (file)
@@ -86,7 +86,7 @@ done:
 
        sprintf(tmp, "%llu", (unsigned long long) num);
        decimals = maxlen - strlen(tmp);
-       if (decimals <= 1) {
+       if ((int)decimals <= 1) {
                if (carry)
                        num++;
                goto done;