C++ Maximum valid memory address
c++, pointers
Solution
From the standard:
c++11
5.9 Relational operators [expr.rel]
If two pointers point to elements of the same array or one beyond the end of the array, the pointer to the object with the higher subscript compares higher.
So you don't need to worry; a conformant implementation will ensure that the past-the-end pointer compares correctly to the rest of the array. In addition,
3.7.4.1 Allocation functions [basic.stc.dynamic.allocation]
[...] The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type with a fundamental alignment requirement (3.11) and then used to access the object or array in the storage allocated [...]
The implication is that the pointer returned should be able to be treated as the pointer to the beginning of an array of appropriate size, so 5.9 continues to hold. This would be the case if the allocation function call is the result of calling `operator new[]` (5.3.4:5).
As a practical matter, if you're on a platform where it is conceivable for the allocator to (non-conformantly) return a block of memory ending at `0xFFFFFFFF`, you could in most cases write
if (p != end)
Problem
I often see code that adds a value, such as a length to a pointer, and then uses this value, e.g. ``` T* end = buffer + bufferLen;//T* + size_t if (p < end) ``` However, is it possible for the buffer to have been allocated near enough the end of memory that "buffer + bufferLen" may overflow (e.g. 0xFFFFFFF0 + 0x10), resulting in "p < end" being false even if p was a valid element address (e.g. 0xFFFFFFF8). If it is possible, how can it be avoided when I see many things that work with a begin/end range where end next element after the last one