Skip to content

Commit 981096f

Browse files
authored
bpo-30242: resolve some undefined behaviours in struct (#1418)
1 parent 7c278a5 commit 981096f

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

Modules/_struct.c

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -543,7 +543,7 @@ np_ubyte(char *p, PyObject *v, const formatdef *f)
543543
"ubyte format requires 0 <= number <= 255");
544544
return -1;
545545
}
546-
*p = (char)x;
546+
*(unsigned char *)p = (unsigned char)x;
547547
return 0;
548548
}
549549

@@ -864,6 +864,7 @@ bp_int(char *p, PyObject *v, const formatdef *f)
864864
{
865865
long x;
866866
Py_ssize_t i;
867+
unsigned char *q = (unsigned char *)p;
867868
if (get_long(v, &x) < 0)
868869
return -1;
869870
i = f->size;
@@ -876,7 +877,7 @@ bp_int(char *p, PyObject *v, const formatdef *f)
876877
#endif
877878
}
878879
do {
879-
p[--i] = (char)x;
880+
q[--i] = (unsigned char)(x & 0xffL);
880881
x >>= 8;
881882
} while (i > 0);
882883
return 0;
@@ -887,6 +888,7 @@ bp_uint(char *p, PyObject *v, const formatdef *f)
887888
{
888889
unsigned long x;
889890
Py_ssize_t i;
891+
unsigned char *q = (unsigned char *)p;
890892
if (get_ulong(v, &x) < 0)
891893
return -1;
892894
i = f->size;
@@ -897,7 +899,7 @@ bp_uint(char *p, PyObject *v, const formatdef *f)
897899
RANGE_ERROR(x, f, 1, maxint - 1);
898900
}
899901
do {
900-
p[--i] = (char)x;
902+
q[--i] = (unsigned char)(x & 0xffUL);
901903
x >>= 8;
902904
} while (i > 0);
903905
return 0;
@@ -1077,6 +1079,7 @@ lp_int(char *p, PyObject *v, const formatdef *f)
10771079
{
10781080
long x;
10791081
Py_ssize_t i;
1082+
unsigned char *q = (unsigned char *)p;
10801083
if (get_long(v, &x) < 0)
10811084
return -1;
10821085
i = f->size;
@@ -1089,7 +1092,7 @@ lp_int(char *p, PyObject *v, const formatdef *f)
10891092
#endif
10901093
}
10911094
do {
1092-
*p++ = (char)x;
1095+
*q++ = (unsigned char)(x & 0xffL);
10931096
x >>= 8;
10941097
} while (--i > 0);
10951098
return 0;
@@ -1100,6 +1103,7 @@ lp_uint(char *p, PyObject *v, const formatdef *f)
11001103
{
11011104
unsigned long x;
11021105
Py_ssize_t i;
1106+
unsigned char *q = (unsigned char *)p;
11031107
if (get_ulong(v, &x) < 0)
11041108
return -1;
11051109
i = f->size;
@@ -1110,7 +1114,7 @@ lp_uint(char *p, PyObject *v, const formatdef *f)
11101114
RANGE_ERROR(x, f, 1, maxint - 1);
11111115
}
11121116
do {
1113-
*p++ = (char)x;
1117+
*q++ = (unsigned char)(x & 0xffUL);
11141118
x >>= 8;
11151119
} while (--i > 0);
11161120
return 0;

0 commit comments

Comments
 (0)