Py_CLEAR and Py_SETREF without UB

Can someone explain to me why Py_CLEAR and Py_SETREF don’t have UB (ifndef _Py_TYPEOF)? Am I missing something from the C standard, or memcpy from NULL allowed?

The relevant lines of Py_CLEAR are this:

            PyObject *_null_ptr = _Py_NULL; \
            memcpy(_tmp_op_ptr, &_null_ptr, sizeof(PyObject*)); \

This doesn’t memcpy from a null pointer, this copies a null pointer, i.e. we are passing in a pointer to a NULL pointer to memcpy. Py_SETREF is similar. Watch for the extra &.

5 Likes

Oh, I see now! I should sleep at night and not ask dumb questions!
Thanks for explanation!

For those who were wondering about the use of memcpy here, this is the explanation as outlined in the source comments:

And the reason _Py_TYPEOF might not be available is that it relies on non-standard C:

(however, C23 has typeof which will probably be usable for this in CPython in a few years, while C++ has decltype and auto which are likely alternatives for this use case :slight_smile: )

Edit: even recent MSVC seems to have __typeof__

5 Likes