Skip to content

ctypes: NULL-dereference when using py_result restype #132417

Closed
@NicolasT

Description

@NicolasT

Crash report

What happened?

When using ctypes with a function which returns a PyObject *, using restype ctypes.py_object, and the function returns NULL, there's a Py_DECREF of the result, leading to a segfault:

import ctypes
PyErr_Occurred = ctypes.pythonapi.PyErr_Occurred
PyErr_Occurred.argtypes = []
PyErr_Occurred.restype = ctypes.py_object
PyErr_Occurred()

The issue lies in GetResult: when O_get is the result handler, it calls Py_DECREF on the result value, even though that can be NULL. O_get handles the NULL case correctly, setting an exception if none was set, and passing on the NULL. Code after the Py_DECREF in GetResult also handles the NULL case correctly, so changing the Py_DECREF into a Py_XDECREF makes things work.

Pull request incoming.

CPython versions tested on:

CPython 3.10, CPython 3.13, CPython main branch

Operating systems tested on:

Linux

Output from running 'python -VV' on the command line:

Python 3.14.0a7+ (heads/main-dirty:deda47d6e18, Apr 11 2025, 20:18:59) [GCC 14.2.1 20240912 (Red Hat 14.2.1-3)]

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirtopic-ctypestype-crashA hard crash of the interpreter, possibly with a core dump

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions