首页 > 解决方案 > How do you force a size limit to prevent format truncation?

问题描述

submission.c:112:32: error: '%02d' directive output may be truncated writing between 2 and 3 bytes into a
region of size between 0 and 2 [-Werror=format-truncation=]
 snprintf(strTime, 5, "%02d:%02d", minFormed, secFormed);
                            ^~~~
submission.c:112:26: note: directive argument in the range [-59, 59]     snprintf(strTime, 5, "%02d:%02d", minFormed, secFormed);
                      ^~~~~~~~~~~
submission.c:112:5: note: 'snprintf' output between 6 and 9 bytes into a destination of size 5
 snprintf(strTime, 5, "%02d:%02d", minFormed, secFormed);
 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I have 2 variables, minFormed and secFormed, both of which are integers.

Through this, I don't believe either of them could be more than 2 bytes each. The timer format should be "00:00" so that's 5 bytes. How do I force the secFormed part to only be 2 bytes?

EDIT: Sorry it was late and forgot to show more code

char * getCurrentTime (void) {
    double time = ( overflow_counter * 256.0 + TCNT0 ) * PRESCALE  / FREQ;
    int timePassed = (int)(floor(time));
    int secFormed = timePassed % 60;
    int minFormed = timePassed / 60;
    char strTime[5];
    snprintf(strTime, 5, "%02d:%02d", minFormed, secFormed);
    return strTime;
}

The timer should really not exceed 99:59 because it's for a game that can be played in a couple of minutes, so some sort of time limitation could be implemented.

Edit: Error after changing string buffer to a size of 6

submission.c:109:32: error: '%02d' directive output may be truncated writing between 2 and 3 bytes into a
region of size between 1 and 3 [-Werror=format-truncation=]
 snprintf(strTime, 6, "%02d:%02d", minFormed, secFormed);
                            ^~~~submission.c:109:26: note: directive argument in the range [-59, 59]     snprintf(strTime, 6, "%02d:%02d", minFormed, secFormed);                          ^~~~~~~~~~~
submission.c:109:5: note: 'snprintf' output between 6 and 9 bytes into a destination of size 6
 snprintf(strTime, 6, "%02d:%02d", minFormed, secFormed);
 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

标签: c

解决方案


我只是在这里猜测,因为您没有提供Minimal, Complete, and Verifiable Example

您似乎将长度5作为缓冲区大小的参数传递。那是包括字符串终止符的缓冲区大小。

这个snprintf(和家庭)参考

bufsz - 最多bufsz - 1可以写入字符,加上空终止符

您的字符串是包括终止符在内的六个字符,因此您需要一个至少六个字符的缓冲区并告知snprintf该大小。

哦,关于范围的注释是因为你使用有符号整数,所以范围也包括负数,这意味着额外的空间。您可能应该改用unsigned intformat "%02u"


推荐阅读