c - 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);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
解决方案
我只是在这里猜测,因为您没有提供Minimal, Complete, and Verifiable Example。
您似乎将长度5
作为缓冲区大小的参数传递。那是包括字符串终止符的缓冲区大小。
bufsz
- 最多bufsz - 1
可以写入字符,加上空终止符
您的字符串是包括终止符在内的六个字符,因此您需要一个至少六个字符的缓冲区并告知snprintf
该大小。
哦,关于范围的注释是因为你使用有符号整数,所以范围也包括负数,这意味着额外的空间。您可能应该改用unsigned int
format "%02u"
。
推荐阅读
- dart - 我怎样才能让 BottomNavigationBar 粘在键盘颤动的顶部
- winapi - 是否可以按 FIFO 顺序将自定义消息放入 win32 消息队列中?
- python - 在 TensorFlow 对象检测 API 中获取类和概率
- c++ - 用于双链接结构的c ++堆排序
- javascript - 如何将 chai-as-promised 与 Typescript 一起使用?
- excel - Excel 数据透视表 - 如何排列字段以对字段求和,同时忽略来自另一个不相关字段的重复行
- json - 在 QJSonArray 中搜索项目
- javascript - 将 SnapshotChanges 与 CombineLatest 一起使用
- java - Java 无法推断“类”<> 的类型参数
- php - PHP 中的 iCloud Web 服务服务器到服务器身份验证