3 ms·
There's a weirdo thing with array allocation in C++ at least which makes it valid to use arrays with all of the std:: algorithms that take a start and end param
by ekidd 15y ago
There's a weirdo thing with array allocation in C++ at least which makes it valid to use arrays with all of the std:: algorithms that take a start and end parameter.
The actual rule is pretty subtle, and I don't have a copy of the C++ standard in front of me. But let's see if I can remember the precise rule.
Given an array arr with length len, you're allowed to create the pointer arr+len. This is the end pointer you see everywhere in modern C++ APIs. However, if you try to deference arr+len, or try to create the pointer arr+len+1, the result is undefined. Typically, the former might point to a locked page, and the latter might overflow the pointer size. But if your compiler applies very aggressive optimizations, even stranger stuff can happen when you rely on undefined behavior:
http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
In the memchr example, the code potentially writes to arr+len, which has a decent chance of temporarily corrupting the implementation-dependent internal headers of the next heap block. In the presence of threads, this would very occasionally corrupt the internal state of new and delete, and debugging it would be a stupendously painful experience.