我正在使用sprintf()
创建一个字符串,literal
是一个整数。
char tag[16];
sprintf(tag, "Literal - %d", literal);
但是项目制造商正在考虑将所有警告视为错误并提出错误:
error: ‘%d’ directive writing between 1 and 11 bytes into a region of size 6 [-Werror=format-overflow=]
sprintf(tag, "Literal - %d", literal); //snprintf(tag, 16, "Literal - %d", literal);
^~
apps/ziptest/test_literals_lzma.c:42:15: note: directive argument in the range [-2147483648, 255] sprintf(tag, "Literal - %d", literal); //snprintf(tag, 16, "Literal
- %d", literal);
^~~~~~~~~~~~~~
apps/ziptest/test_literals_lzma.c:42:2: note: ‘sprintf’ output between 12 and 22 bytes into a destination of size 16 sprintf(tag, "Literal - %d", literal); //snprintf(tag, 16, "Literal - %d", literal); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors Makefile:370: recipe for target
可以避免这种警告吗? (文字范围是0到255)
最佳答案
和
sprintf(tag, "Literal - %d", literal);
因为您的缓冲区是16个字节,前缀是10个字节,所以剩下5个字节来写
literal
的字符串表示形式。由于
int
在您的系统上可能是32位,因此最大范围是2147483647,负数范围是-2147483648(11个字符),编译器会警告您(因为它能够计算所有大小)现在,由于您知道范围不能在0-255之外,因此只需减小
literal
的大小即可,例如,将其声明为unsigned short
(short
可以是字符串的6个字节长:-32768
如注释中指出的chux),因此您有余地您的值(value)。unsigned short literal = 123;
sprintf(tag, "Literal - %hu", literal);
(您可以使用
unsigned char
格式说明符,使用范围从0到255的%hhu
)或仅在打印时进行转换:
sprintf(tag, "Literal - %hu", (unsigned short)literal);
(
%u
可能也可以工作,但是取决于编译器的智能程度:它仅分析变量args的格式还是大小?)现在我们知道了为什么会出现警告,我们不要忘记最明显的解决方案:让我们定义一个足够大的数组。
char tag[25]; // 21 would have been okay
应该做。将其剃得太近通常不是一个好主意,除非您的资源不足。
关于c - 如何禁止sprintf()警告 'directive writing between 1 and 11 bytes into a region of size 6 ',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51697753/