int* a = new int[5] - 1;
This line by itself invokes undefined behavior according to the C++ standard because a is an invalid pointer and not one-past-the-end. At the same time this is a zero overhead way of making a 1-based array (first element is a[1]) which I need for a project of mine.
I’m wondering if this is something that I need to avoid or if the C++ standard is just being conservative to support some bizarre architectures that my code is never going to run on anyway. So the question is, on what architectures will this be a problem? Are any of those widespread?
Edit: To see that the line above does indeed invoke undefined behavior, take a look at this question.
Edit: Dennis Zickefoose points out that compilers are allowed to do anything when undefined behavior is invoked, so both the compiler and the CPU have to offer guarantees beyond the C++ standard for code like this to work. I’m expanding the question to whether any modern C++ compilers have this issue.
The hardware for doing the checks is present in all x86 processors, we are just not using it at the moment in the most popular operating systems.
If you use a segmented memory architecture, which we did for 16-bit systems, an allocation is not unlikely to return the address
segment:0. In that case you just cannot subtract anything from that address!Here is a starting point for reading about segmented memory and why loading an invalid segment is not possible:
http://en.wikipedia.org/wiki/Segment_descriptor
You have to decide if this unlikely to happen for your code, or if you perhaps can define an overloaded
operator[]that handles the offset for you.