c++ - 更正 "format string is not a string literal"警告

标签 c++ clang

我的代码中有一个警告让我发疯:

int vasprintf_wrapper(char** bufptr, const char* fmt, va_list ap)
{
    // Do stuff...
    // ...
    return vasprintf(bufptr, fmt, ap);
}

Clang (3.6.0),提示“格式字符串不是字符串文字”,指的是正在转发的 fmt 参数。

天真地,我试图:

return vasprintf(bufptr, reinterpret_cast<const char[]>(fmt), ap);

当然不能编译。

我该怎么办?完全禁用警告不是一种选择。我想要警告。但在这种情况下,我想告诉编译器我知道我在做什么(撇开“著名的遗言”笑话......)

最佳答案

使用 __attribute__ 标志指示参数是 printf 样式的格式。例如:

__attribute__((__format__ (__printf__, 2, 0)))
int vasprintf_wrapper(char** bufptr, const char* fmt, va_list ap)
{
  ...
}

最后一个参数 (0) 禁用对 va_list 的检查。

来自文档:

format (archetype, string-index, first-to-check)

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.

The parameter string-index specifies which argument is the format string argument (starting from 1).

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.

另见:

关于c++ - 更正 "format string is not a string literal"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36120717/

相关文章:

c++ - 函数参数中的 `type_alias<char[N]>{}` VS `char[N]{}`

c++ makefile解释(其中使用的依赖项和宏)?

c++ - 在未来的 C++1x 中将如何实现最小垃圾收集支持?

c++ - 确定模板化结构所保存的数据类型

c++ - OpenGL在一个窗口中提供多个渲染上下文

c - 如何使用 Clang 和 MinGW C/C++ 库编译代码? (float.h 的特殊问题)

clang - 如何为 LLVM 指定自定义 stdlib 目录

android - 让 OpenCV 支持 NDK 在 Android Studio 中工作

apache - 使用 LLVM Plus 自定义 channel 和自定义库编译 Apache Server

C++ 模块 TS 和 CMake