Skip to content

Commit b946af5

Browse files
Check for NULL before the pointer aligning in fastsearch_memchr_1char.
There is no guarantee that NULL is aligned.
2 parents 45cb7f6 + 18ba40b commit b946af5

1 file changed

Lines changed: 10 additions & 15 deletions

File tree

‎Objects/stringlib/fastsearch.h‎

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,25 +38,18 @@ STRINGLIB(fastsearch_memchr_1char)(const STRINGLIB_CHAR* s, Py_ssize_t n,
3838
STRINGLIB_CHAR ch, unsigned char needle,
3939
Py_ssize_t maxcount, int mode)
4040
{
41-
void *candidate;
42-
const STRINGLIB_CHAR *found;
43-
44-
#define DO_MEMCHR(memchr, s, needle, nchars) do { \
45-
candidate = memchr((const void *) (s), (needle), (nchars) * sizeof(STRINGLIB_CHAR)); \
46-
found = (const STRINGLIB_CHAR *) _Py_ALIGN_DOWN(candidate, sizeof(STRINGLIB_CHAR)); \
47-
} while (0)
48-
4941
if (mode == FAST_SEARCH) {
5042
const STRINGLIB_CHAR *ptr = s;
5143
const STRINGLIB_CHAR *e = s + n;
5244
while (ptr < e) {
53-
DO_MEMCHR(memchr, ptr, needle, e - ptr);
54-
if (found == NULL)
45+
void *candidate = memchr((const void *) ptr, needle, (e - ptr) * sizeof(STRINGLIB_CHAR));
46+
if (candidate == NULL)
5547
return -1;
56-
if (sizeof(STRINGLIB_CHAR) == 1 || *found == ch)
57-
return (found - s);
48+
ptr = (const STRINGLIB_CHAR *) _Py_ALIGN_DOWN(candidate, sizeof(STRINGLIB_CHAR));
49+
if (sizeof(STRINGLIB_CHAR) == 1 || *ptr == ch)
50+
return (ptr - s);
5851
/* False positive */
59-
ptr = found + 1;
52+
ptr++;
6053
}
6154
return -1;
6255
}
@@ -66,9 +59,11 @@ STRINGLIB(fastsearch_memchr_1char)(const STRINGLIB_CHAR* s, Py_ssize_t n,
6659
faster than our hand-written loop in FASTSEARCH below */
6760
else if (mode == FAST_RSEARCH) {
6861
while (n > 0) {
69-
DO_MEMCHR(memrchr, s, needle, n);
70-
if (found == NULL)
62+
const STRINGLIB_CHAR *found;
63+
void *candidate = memrchr((const void *) s, needle, n * sizeof(STRINGLIB_CHAR));
64+
if (candidate == NULL)
7165
return -1;
66+
found = (const STRINGLIB_CHAR *) _Py_ALIGN_DOWN(candidate, sizeof(STRINGLIB_CHAR));
7267
n = found - s;
7368
if (sizeof(STRINGLIB_CHAR) == 1 || *found == ch)
7469
return n;

0 commit comments

Comments
 (0)