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);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我有两个变量minFormed
和secFormed
,它们都是整数。
通过这种方式,我认为它们每个都不超过2个字节。计时器格式应为“ 00:00”,即5个字节。如何强制secFormed
部分只有2个字节?
编辑:对不起,太晚了,忘了显示更多代码
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;
}
计时器实际上不应超过99:59,因为它是用于可以在几分钟内玩的游戏,因此可以实施某种时间限制。
编辑:将字符串缓冲区更改为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);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
答案 0 :(得分:3)
在这里我只是 猜测 ,因为您没有提供Minimal, Complete, and Verifiable Example。
似乎您正在传递长度5
作为缓冲区大小的参数。那就是缓冲区大小包括字符串终止符。
来自this snprintf
(and family) reference:
bufsz
-最多可以写入bufsz - 1
个字符,加上空终止符
您的字符串是六个字符,包括终止符,因此您需要至少六个字符的缓冲区,并告诉snprintf
该大小。
哦,关于范围的注释是因为您使用了 signed 整数,所以范围也包括负数,这意味着多余的空间。您可能应该改用unsigned int
和格式"%02u"
。