IAmPropper
IAmPropper

Reputation: 43

UB with reinterpret_cast

Am i allowed to do this safely, assuming func is only ever called with &container_instance.bar?


struct foo_t { int val; };
struct bar_t { int val; };

struct container
{
    foo_t foo;
    bar_t bar;
};

void func(bar_t* b)
{
    std::uintptr_t addr_of_b = reinterpret_cast<std::uintptr_t>(b);
    // get address of foo
    addr_of_b -= offsetof(container, bar);
    foo_t* f = reinterpret_cast<foo_t*>(addr_of_b);

    // access f
    f->val = 42;
}

From cppreference (reinterpret_cast) i found these two quotes, which seem to be somewhat applicable in this scenario. However, item 3) does not talk about the case when i modify the integral value and item 6) seems to be concerned with accessing foo_t* directly from the address of bar_t*. Is the above mentioned scenario defined somewhere?

  1. A value of any integral or enumeration type can be converted to a pointer type. A pointer converted to an integer of sufficient size and back to the same pointer type is guaranteed to have its original value, otherwise the resulting pointer cannot be dereferenced safely (the round-trip conversion in the opposite direction is not guaranteed; the same pointer may have multiple integer representations)
  1. An glvalue expression of type T1 can be converted to reference to another type T2. The result is that of *reinterpret_cast<T2*>(p), where p is a pointer of type “pointer to T1” to the object or function designated by expression. No temporary is created, no copy is made, no constructors or conversion functions are called. The resulting reference can only be accessed safely if it is type-accessible.

Upvotes: 0

Views: 100

Answers (0)

Related Questions