gpt4 book ai didi

c - 如何强制限制大小以防止格式截断?

转载 作者:行者123 更新时间:2023-11-30 18:34:13 25 4
gpt4 key购买 nike

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);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我有 2 个变量,minFormedsecFormed,它们都是整数。

通过这个,我不相信它们中的任何一个都可以超过 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);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

最佳答案

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

看来您正在传递长度5作为缓冲区大小的参数。这是缓冲区大小包括字符串终止符。

来自this snprintf (and family) reference :

bufsz - up to bufsz - 1 characters may be written, plus the null terminator

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

哦,关于范围的注释是因为您使用有符号整数,因此范围也包含负数,这意味着额外的空间。您可能应该使用 unsigned int 代替,格式为 "%02u"

关于c - 如何强制限制大小以防止格式截断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52948256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com