[issue45325] Allow "p" in Py_BuildValue

STINNER Victor report at bugs.python.org
Thu Sep 30 05:04:20 EDT 2021


STINNER Victor <vstinner at python.org> added the comment:

> I think that the risk for other formatting parameters is smaller, because you know, that there are different formatting parameters for different integer and floating point types, and for pointers, and you know that you should care about truncation and overflow if the type of the argument is different from the type of the parameter.

IMO such problem can be solved with documentation.

Pablo: can you try to explain the problem in the documentation, and maybe provide an example in the doc showing how to avoid it?

I guess that a generic fix is to replace "value" with "value != 0". In C, "expr != 0" is an int, no?

What I understood is that Py_BuildValue("p", value) is problematic if value type is not int.

"!value" or "!!value" also has the issue if I understood correctly. Like:

    long value = 3; Py_BuildValue("p", !value);

I agree with Serhiy that Py_BuildValue() is ok-ish with other formats, but IMO it's the responsibility of the developer to pass the expect type (int for "p" format).

This problem is not specific to Py_BuildValue(). printf() also has exactly the same issue. Such code has an undefined behavior:

  long long x = 1; print("%d\n", x);

You must cast explicitly:

  long long x = 1; print("%d\n", (int)x);

Or use a different format, like:

  long long x = 1; print("%lld\n", x);

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45325>
_______________________________________


More information about the Python-bugs-list mailing list