【问题标题】:format not a string literal and no format arguments [-Wformat-security]格式不是字符串文字,也没有格式参数 [-Wformat-security]
【发布时间】:2014-12-23 06:04:01
【问题描述】:

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

./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 已经存在?

【问题讨论】:

    标签: python c++ string format literals


    【解决方案1】:

    使格式字符串文字明确:

    printf("%s", str);
    

    同样的警告可以用the following snippet复制:

    #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),因为后面跟着两个附加参数。

    【讨论】:

    • 我理解你在 C++ sn-p 上下文中的意思。那么您是说需要更改的代码是:PyErr_Format(PyExc_RuntimeError, mesg); 所以这里需要一个“%s”?
    • @tv49 让编译器满意,是的。第一个应该需要两个。
    • PyErr_Format("%s %s", PyExc_RuntimeError, mesg); 你是这个意思吗?抱歉,我对 Linux 很陌生。
    • 第一个:PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg); 第二个是PyErr_Format(PyExc_RuntimeError, "%s", mesg);
    • 当我在fedora 23 x86_64 中安装wxPython 2.8.12.1 时,这个源码包中也有PyErr_Format(PyExc_RuntimeError, mesg); 之类的代码。宏 A 的解决方案解决了我的问题。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 2010-12-13
    • 2011-05-24
    • 2011-08-12
    • 2013-08-25
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多