GeezerVison is showing github.com — BUG: Fix unaligned memory access in `npy_memchr`. · saran-t/numpy@01f1ac9
File tree
Expand file treeCollapse file tree
Open diff view settings
numpy/core/src/multiarray
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: numpy/core/src/multiarray/common.h +23-9Lines changed: 23 additions & 9 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -269,17 +269,31 @@ npy_memchr(char * haystack, char needle, |
269 | 269 | else { |
270 | 270 | /* usually find elements to skip path */ |
271 | 271 | if (!NPY_ALIGNMENT_REQUIRED && needle == 0 && stride == 1) { |
272 | | - /* iterate until last multiple of 4 */ |
273 | | - char * block_end = haystack + size - (size % sizeof(unsigned int)); |
274 | | - while (p < block_end) { |
275 | | - unsigned int v = *(unsigned int*)p; |
276 | | - if (v != 0) { |
277 | | - break; |
278 | | - } |
279 | | - p += sizeof(unsigned int); |
| 272 | + /* find the first sizeof(unsigned int)-aligned block */ |
| 273 | + npy_intp first_block_offset = Py_MIN( |
| 274 | + sizeof(unsigned int) - (npy_uintp)p % sizeof(unsigned int), |
| 275 | + size); |
| 276 | + char * first_block = p + first_block_offset; |
| 277 | + while (p < first_block && *p == 0) { |
| 278 | + p++; |
280 | 279 | } |
281 | | - /* handle rest */ |
282 | 280 | subloopsize = (p - haystack); |
| 281 | + |
| 282 | + if (subloopsize < size && *p == 0) { |
| 283 | + /* iterate until last multiple of sizeof(unsigned int) */ |
| 284 | + npy_intp adjusted_size = size - first_block_offset; |
| 285 | + char * block_end = p + |
| 286 | + adjusted_size - (adjusted_size % sizeof(unsigned int)); |
| 287 | + while (p < block_end) { |
| 288 | + unsigned int v = *(unsigned int*)p; |
| 289 | + if (v != 0) { |
| 290 | + break; |
| 291 | + } |
| 292 | + p += sizeof(unsigned int); |
| 293 | + } |
| 294 | + /* handle rest */ |
| 295 | + subloopsize = (p - haystack); |
| 296 | + } |
283 | 297 | } |
284 | 298 | while (subloopsize < size && *p == needle) { |
285 | 299 | subloopsize++; |
|