格式不是字符串文字和格式参数[-Wformat-security] [英] format not a string literal and no format arguments [-Wformat-security]

查看:1815
本文介绍了格式不是字符串文字和格式参数[-Wformat-security]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定是什么原因造成这个错误

$ $ p $ ./ lhapdf_wrap.cc:在函数中void SWIG_Python_AddErrorMsg(const char *)':
./lhapdf_wrap.cc:877:62:警告:格式太多参数[-Wformat-extra-args]
PyErr_Format(type,%s,PyString_AsString(old_str) ,mesg);

./lhapdf_wrap.cc:881:42:warning:格式不是字符串,也不是格式参数[-Wformat-security]
PyErr_Format(PyExc_RuntimeError,mesg);

代码是:

  SWIGRUNTIME void 
SWIG_Python_AddErrorMsg(const char * mesg)
{
PyObject * type = 0;
PyObject * value = 0;
PyObject * traceback = 0; (PyErr_Occurred())PyErr_Fetch(& type,& value,& traceback);

if
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);




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

解决方案

使格式字符串字面值明确:

  printf(%s,str); 






同样的警告可以用以下片段

  #include< stdio.h> 

int main()
{
char str [] =hello;
printf(str);

$ b main.cpp:6:12:warning:格式字符串不是字符串文字(可能不安全)
[-Wformat-security]
<编译器无法验证 str 是否包含一个

>

%s



第一个警告有一个不匹配的地方:不足的格式说明符(例如另一个%s ),因为有两个额外的参数。


I am not sure what is causing this error

./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);
                                          ^

The code is:

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);
  }
}

I have looked into the string literal error but the %s is already present?

解决方案

Make the format string literal explicit:

printf("%s", str);


The same warning can be reproduced with 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]

The compiler cannot verify if str contains a %s.

The first warning has a mismatch instead: insufficient format specifiers (e.g. another %s) in the string literal, since two additional argument follow.

这篇关于格式不是字符串文字和格式参数[-Wformat-security]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆