format不是字符串文字,也没有格式参数[-Wformat security]

format not a string literal and no format arguments [-Wformat-security]

本文关键字:参数 有格式 -Wformat security 字符串 文字 format      更新时间:2023-10-16

我不确定是什么导致了这个错误

./lhapdf_wrap.cc: In function ‘void SWIG_Python_AddErrorMsg(const char*)’:
./lhapdf_wrap.cc:877:62: warning: too many arguments for format [-Wformat-extra-args]
     PyErr_Format(type, "%s", PyString_AsString(old_str), mesg);
                                                              ^
./lhapdf_wrap.cc:881:42: warning: format not a string literal and no format arguments [-Wformat-security]
     PyErr_Format(PyExc_RuntimeError, mesg);
                                          ^

代码为:

SWIGRUNTIME void
SWIG_Python_AddErrorMsg(const char* mesg)
{
  PyObject *type = 0;
  PyObject *value = 0;
  PyObject *traceback = 0;
  if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback);
  if (value) {
    PyObject *old_str = PyObject_Str(value);
    PyErr_Clear();
    Py_XINCREF(type);
    PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);
    Py_DECREF(old_str);
    Py_DECREF(value);
  } else {
    PyErr_Format(PyExc_RuntimeError, mesg);
  }
}

我已经查看了字符串文字错误,但%s已经存在?

使格式字符串文字显式:

printf("%s", str);

相同的警告可以通过以下片段重现:

#include <stdio.h>
int main()
{
    char str[] = "hello";
    printf(str);
}
main.cpp:6:12: warning: format string is not a string literal (potentially insecure) 
[-Wformat-security]

编译器无法验证str是否包含%s

第一个警告不匹配:字符串文字中的格式说明符(例如另一个%s)不足,因为后面还有两个额外的参数。