Skip to content

Commit 8b5ce31

Browse files
authored
gh-71810: Fix _PyLong_AsByteArray() undefined behavior (#138873)
Don't read p[-1] when p is an empty string: when n==0.
1 parent 7168e98 commit 8b5ce31

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

Objects/longobject.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1214,8 +1214,14 @@ _PyLong_AsByteArray(PyLongObject* v,
12141214
just above didn't get to ensure there's a sign bit, and the
12151215
loop below wouldn't add one either. Make sure a sign bit
12161216
exists. */
1217-
unsigned char msb = *(p - pincr);
1218-
int sign_bit_set = msb >= 0x80;
1217+
int sign_bit_set;
1218+
if (n > 0) {
1219+
unsigned char msb = *(p - pincr);
1220+
sign_bit_set = msb >= 0x80;
1221+
}
1222+
else {
1223+
sign_bit_set = 0;
1224+
}
12191225
assert(accumbits == 0);
12201226
if (sign_bit_set == do_twos_comp)
12211227
return 0;

0 commit comments

Comments
 (0)