Skip to content

__str__ is called on an ininitialized instance when constructor arguments invalid #283

@jagerman

Description

@jagerman

If a class with a __str__ method is constructed with invalid constructor arguments, the __str__ method is called on an uninitialized object instance when attempting to generate the exception message, which will print random values and/or segfault, depending on what the __str__ mapped function actually does with the object.

Here's a short example:

    class StrIssue {
    public:
        StrIssue(int i) : val{i} {}
        StrIssue() : StrIssue(-1) {}
        int value() const { return val; }
    private:
        int val;
    };


    py::class_<StrIssue> si(m2, "StrIssue");
    si  .def(py::init<int>())
        .def(py::init<>())
        .def("__str__", [](const StrIssue &si) {
                std::cout << "StrIssue.__str__ called" << std::endl;
                return "StrIssue[" + std::to_string(si.value()) + "]";
                })
        ;

In python:

s = StrIssue("no", "such", "constructor")

This will give:

StrIssue.__str__ called
Traceback (most recent call last):
  File "issues.py", line 77, in <module>
    print(StrIssue("no", "such", "constructor"))
TypeError: Incompatible function arguments. The following argument types are supported:
    1. (example.issues.StrIssue, int) -> NoneType
    2. (example.issues.StrIssue) -> NoneType
    Invoked with: StrIssue[38300560], no, such, constructor

Changing val to something with a pointer (e.g. some stl container) will cause a segfault instead of the random number (38300560 in this case).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions