8000 gh-111178: fix UBSan for `custom.c` examples by picnixz · Pull Request #131606 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-111178: fix UBSan for custom.c examples #131606

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 24, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update Doc/extending/newtypes_tutorial.rst
Co-authored-by: Petr Viktorin <encukou@gmail.com>
  • Loading branch information
picnixz and encukou authored Mar 24, 2025
commit d3b5c48d31a79afec2574d350bd0933e7f75c6c6
24 changes: 22 additions & 2 deletions Doc/extending/newtypes_tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -273,8 +273,28 @@ be an instance of a subclass.
.. note::
The explicit cast to ``CustomObject *`` above is needed because we defined
``Custom_dealloc`` to take a ``PyObject *`` argument, as the ``tp_dealloc``
function pointer expects to receive a ``PyObject *`` argument. Otherwise,
this would result in an undefined behaviour at runtime!
function pointer expects to receive a ``PyObject *`` argument.
By assigning to the the ``tp_dealloc`` slot of a type, we declare
that it can only be called with instances of our ``CustomObject``
class, so the cast to ``(CustomObject *)`` is safe.
This is object-oriented polymorphism, in C!

In existing code, or in previous versions of this tutorial,
you might see similar functions take a pointer to the subtype
object structure (``CustomObject*``) directly, like this::

Custom_dealloc(CustomObject *self)
{
Py_XDECREF(self->first);
Py_XDECREF(self->last);
Py_TYPE(self)->tp_free((PyObject *) self);
}
...
.tp_dealloc = (destructor) Custom_dealloc,

This does the same thing on all architectures that CPython
supports, but according to the C standard, it invokes
undefined behavior.

We want to make sure that the first and last names are initialized to empty
strings, so we provide a ``tp_new`` implementation::
Expand Down
Loading
0