From: Victor Stinner Date: Sun, 14 Sep 2025 09:25:53 +0000 (+0200) Subject: gh-71810: Fix _PyLong_AsByteArray() undefined behavior (#138873) X-Git-Tag: v3.15.0a1~380 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=8b5ce31c2b44d9bf82e6119e90a52dd530bfd1db;p=thirdparty%2FPython%2Fcpython.git gh-71810: Fix _PyLong_AsByteArray() undefined behavior (#138873) Don't read p[-1] when p is an empty string: when n==0. --- diff --git a/Objects/longobject.c b/Objects/longobject.c index 63b48572ff20..dba190d840ca 100644 --- a/Objects/longobject.c +++ b/Objects/longobject.c @@ -1214,8 +1214,14 @@ _PyLong_AsByteArray(PyLongObject* v, just above didn't get to ensure there's a sign bit, and the loop below wouldn't add one either. Make sure a sign bit exists. */ - unsigned char msb = *(p - pincr); - int sign_bit_set = msb >= 0x80; + int sign_bit_set; + if (n > 0) { + unsigned char msb = *(p - pincr); + sign_bit_set = msb >= 0x80; + } + else { + sign_bit_set = 0; + } assert(accumbits == 0); if (sign_bit_set == do_twos_comp) return 0;