c - 如何禁止sprintf()警告 'directive writing between 1 and 11 bytes into a region of size 6 '

标签 c

我正在使用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/

相关文章:

c - zlib raw deflate/inflate 输出不匹配

c - C 中的静态和动态内存何时分配和取消分配?

c - 我的 fma() 坏了吗?

c - 数组中的字符串到另一个数组中

C 函数有时返回太慢

c - 使用稀疏矩阵的检查断点算法

在字节数组和 unsigned long 之间复制

c - 什么是替换 2D (10x10) int 数组中重复元素的有效方法

C语言编程如何获取树中的叶子列表

c - C 中的结构数组