From c4ee83c4987192bb7528ba0bb3be063fb753574e Mon Sep 17 00:00:00 2001 From: Thomas Braun Date: Fri, 18 Jul 2025 18:50:33 +0200 Subject: [PATCH] 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 --- include/pybind11/pybind11.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/include/pybind11/pybind11.h b/include/pybind11/pybind11.h index 06be7f1d4..f57a7cde0 100644 --- a/include/pybind11/pybind11.h +++ b/include/pybind11/pybind11.h @@ -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;