2

Suppose I have a valid pointer p0:

T a[10];
T* p0 = &a[0];

I know that I can safely round-trip-cast it like this:

reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p0)) == p0;

But is it safe to do the following?

T* p1 = reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p0) + sizeof(T));

i.e. can I be sure that there is no UB and that p1 == &a[1]?

7
  • What do you mean by "can I be sure that there is no unsigned byte"? Where? Commented May 21, 2015 at 9:45
  • 4
    @theV0ID UB is a popular acronym in C++ world for Undefined Behavior. Commented May 21, 2015 at 9:46
  • I'm pretty sure that'll fail on word-addressed systems, where incrementing an address by n makes it point n*wordsize bytes further. Commented May 21, 2015 at 9:46
  • @theV0ID: Undefined behavior, not unsigned byte. Commented May 21, 2015 at 9:47
  • 1
    duplicate: stackoverflow.com/questions/22624472/… Commented May 21, 2015 at 9:58

1 Answer 1

3

This is implementation-defined behaviour. Your compiler should document whether or not pointer arithmetic is equivalent to integer arithmetic on the converted numeric values of pointers. That should be the case on modern computers with a "flat" byte-addressed memory space; but it's not guaranteed to work portably on all platforms.

Using char* rather than uintptr_t will work portably, as long as you stay within the array and ensure the pointer is correctly aligned for T before converting back.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.