3 ms·
If the source string is NUL terminated, however, attempting to access it in units larger than bytes risks attempting to read characters after the NUL. If the NU
by kelnos 15y ago
If the source string is NUL terminated, however, attempting to access it in units larger than bytes risks attempting to read characters after the NUL. If the NUL character is the last byte of a VM (virtual memory) page and the next VM page is not defined, this would cause the process to die from an unwarranted "page not present" fault.
I don't see how that could happen. Are there any machines out there where VM pages are not aligned to some multiple (even 1x) of the CPU's native word size?
If I'm correct in assuming there isn't, then by definition, if the NUL character is the last byte of a page, then it's word-aligned, and you'd read exactly to the end of the page anyway. Alternatively, if you're starting your read on an unaligned address but making your read size a multiple of the CPU word size (in which case you could read past the end of the page), you're not really gaining anything performance-wise.
- nitrogen 15y agoThe page fault problem seems unlikely, but SIMD-optimized versions of functions like strcspn() will read in 8-byte chunks, causing Valgrind's memcheck to complain about invalid reads when you do a strcspn() on a string where length % 8 != 0. As for the original problem, I suspect x86 is relatively unique in its tolerance for unaligned memory accesses. The ARM processor I'm working with will return the wrong data if you try a 16-bit or 32-bit read that is not aligned on a 16-bit or 32-bit boundary. malloc() is supposed to return memory that is aligned to the platform's largest alignment requirement, so it takes a bit of deliberate work to create unaligned accesses. It seems unlikely that a NUL-terminated string will be accessed using unaligned multi-byte reads, since optimized libc functions will take alignment into consideration.