fix:: initialize_generic compiler warning about nullptr dereference (#5756)

When compiling an application using pybind11 3.0.0, GCC 13.3.0 and
python 3.11.13 the following warning is emitted [1]:

  In function 'PyObject* PyCFunction_GET_SELF(PyObject*)',
      inlined from 'void pybind11::cpp_function::initialize_generic(unique_function_record&&, const char*, const std::type_info* const*, pybind11::size_t)' at /opt/conda/lib/python3.11/site-packages/pybind11/include/pybind11/pybind11.h:605:30:
  /opt/conda/include/python3.11/cpython/methodobject.h:50:16: error: potential null pointer dereference [-Werror=null-dereference]
     50 |         return _Py_NULL;
        |                ^~~~~~~~

It stems form the fact that PyCFunction_GET_SELF can return a nullptr.
Let's fail in this case.

[1]: https://gitlab.com/tango-controls/pytango/-/jobs/10671972312#L570
This commit is contained in:
Thomas Braun
2025-07-18 18:50:33 +02:00
committed by GitHub
parent cc69a3789c
commit c4ee83c498

View File

@@ -603,6 +603,10 @@ protected:
if (rec->sibling) {
if (PyCFunction_Check(rec->sibling.ptr())) {
auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
if (self == nullptr) {
pybind11_fail(
"initialize_generic: Unexpected nullptr from PyCFunction_GET_SELF");
}
chain = detail::function_record_ptr_from_PyObject(self);
if (chain && !chain->scope.is(rec->scope)) {
/* Never append a method to an overload chain of a parent class;