c++ - Can std::uintptr_t be used to avoid undefined behavior of out-of-bounds pointer arithmetic? -
now know doing out-of-bounds-pointer-arithmetic has undefined behavior described in so question.
my question is: can workaround such restriction casting std::uintptr_t arithmetic operations , cast pointer? guaranteed work?
for example:
char a[5]; auto u = reinterpret_cast<std::uintptr_t>(a) - 1; auto p = reinterpret_cast<char*>(u + 1); // ok? the real world usage optimizing offsetted memory access -- instead of p[n + offset], want offset_p[n].
edit make question more explicit:
given base pointer p of char array, if p + n valid pointer, reinterpret_cast<char*>(reinterpret_cast<std::uintptr_t>(p) + n) guaranteed yield same valid pointer?
yes, legal, must reinterpret_cast same uintptr_t value char*.
(therefore, you're intending illegal; is, converting different value pointer.)
5.2.10 reinterpret cast
4 . pointer can explicitly converted integral type large enough hold it. mapping function implementation-defined.
5 . value of integral type or enumeration type can explicitly converted pointer. pointer converted integer of sufficient size (if such exists on implementation) , same pointer type have original value;
(note there'd no way, in general, compiler know subtracted 1 , added back.)
Comments
Post a Comment