校正“格式字符串不是字符串文字”。警告 [英] Correcting "format string is not a string literal" warning
问题描述
我的代码中有一条警告令我发疯:
I have a warning in my code that is driving me crazy:
int vasprintf_wrapper(char** bufptr, const char* fmt, va_list ap)
{
// Do stuff...
// ...
return vasprintf(bufptr, fmt, ap);
}
Clang(3.6.0),抱怨格式字符串不是字符串文字,指的是要转发的 fmt
自变量。
Clang (3.6.0), complains with "format string is not a string literal", referring to the fmt
argument that is being forwarded.
天真的,我试图做到:
return vasprintf(bufptr, reinterpret_cast<const char[]>(fmt), ap);
当然不会编译。
我该怎么办?完全禁用警告不是一种选择。我想要警告。但是在这种情况下,我想告诉编译器我知道自己在做什么(笑话)……
What do I do? Disabling the warning altogether is not an option. I want to have the warning. But in this case, I would like to tell the compiler that I know what I'm doing ("famous last words" jokes aside...)
推荐答案
使用 __ attribute __
标志指示参数是 printf
样式的格式。例如:
Indicate a parameter is a printf
-style format using the __attribute__
flag. For example:
__attribute__((__format__ (__printf__, 2, 0)))
int vasprintf_wrapper(char** bufptr, const char* fmt, va_list ap)
{
...
}
最后一个参数( 0
)禁用检查 va_list
。
The last parameter (0
) disables checking for va_list
.
从文档中:
格式(原型,字符串索引,第一个-进行检查)
format
属性指定函数使用 printf
-, scanf
-, strftime
-或 strfmon
风格的参数,应根据格式字符串进行类型检查。
The format
attribute specifies that a function takes printf
-, scanf
-, strftime
-, or strfmon
-style arguments that should be type-checked against a format string.
参数原型
确定格式字符串的解释方式。
The parameter archetype
determines how the format string is interpreted.
参数 string-index
指定哪个参数是格式字符串参数(从1开始)。
The parameter string-index
specifies which argument is the format string argument (starting from 1).
参数首先要检查
是用于检查格式字符串的第一个参数的数字。对于无法检查参数的函数(例如 vprintf
),将第三个参数指定为零。
The parameter first-to-check
is the number of the first argument to check against the format string. For functions where the arguments are not available to be checked (such as vprintf
), specify the third parameter as zero.
另请参见:
- http://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function -属性
- http:/ /clang.llvm.org/docs/AttributeReference.html#format
- http://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes
- http://clang.llvm.org/docs/AttributeReference.html#format
这篇关于校正“格式字符串不是字符串文字”。警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!