5

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?

tv49
  • 79
  • 2
  • 4

1 Answers1

8

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.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Marco A.
  • 43,032
  • 26
  • 132
  • 246
  • I understand what you mean in the context of the C++ snippet. So are you saying the piece of code that needs to be changed is: `PyErr_Format(PyExc_RuntimeError, mesg);` so a '%s' is required here? – tv49 Oct 28 '14 at 18:35
  • @tv49 to make the compiler happy, yes. And two should be required for the first. – Marco A. Oct 28 '14 at 18:38
  • `PyErr_Format("%s %s", PyExc_RuntimeError, mesg);` Do you mean something like that? Sorry I am very new to Linux. – tv49 Oct 28 '14 at 19:24
  • 1
    For the first one: `PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);` while for the second one `PyErr_Format(PyExc_RuntimeError, "%s", mesg);` – Marco A. Oct 28 '14 at 19:27
  • Thank you so much, it is now working. That has helped me a lot. – tv49 Oct 28 '14 at 19:52
  • 1
    When I install [wxPython 2.8.12.1](https://sourceforge.net/projects/wxpython/files/wxPython/2.8.12.1/) in fedora 23 x86_64, there are also code like `PyErr_Format(PyExc_RuntimeError, mesg);` in this source package. Macro A's solution solved my problem. Many thanks. – Nick Dong Apr 08 '17 at 10:34