Here's an example:
#include <cstddef>
#include <iostream>
struct A
{
char padding[7];
int x;
};
constexpr int offset = offsetof(A, x);
int main()
{
A a;
a.x = 42;
char *ptr = (char *)&a;
std::cout << *(int *)(ptr + offset) << '\n'; // Well-defined or not?
}
I always assumed that it's well-defined (otherwise what would be the point of offsetof
), but wasn't sure.
Recently I was told that it's in fact UB, so I want to figure it out once and for all.
Does the example above cause UB or not? If you modify the class to not be standard-layout, does it affect the result?
And if it's UB, are there any workarounds for it (e.g. applying std::launder
)?
This entire topic seems to be moot and underspecified.
Here's some information I was able to find:
Is adding to a “char *” pointer UB, when it doesn't actually point to a char array? - In 2011, CWG confirmed that we're allowed to examine the representation of a standard-layout object through an unsigned char
pointer.
char
pointer can be used insteaed, common sense says it can.Unclear if staring from C++17 std::launder
needs to be applied to the result of the (unsigned char *)
cast. Given that it would be a breaking change, it's probably unnecessarly, at least in practice.
Unclear why C++17 changed offsetof
to conditionally-support non-standard-layout types (used to be UB). It seems to imply that if an implementation supports that, then it also lets you examine the representation of non-standard-layout objects through unsigned char *
.
Do we need to use std::launder when doing pointer arithmetic within a standard-layout object (e.g., with offsetof)? - A question similar to this one. No definitive answer was given.
Here I will refer to C++20 (draft) wording, because one relevant editorial issue was fixed between C++17 and C++20 and also it is possible to refer to specific sentences in HTML version of the C++20 draft, but otherwise there is nothing new in comparison to C++17.
At first, definitions of pointer values [basic.compound]/3:
Every value of pointer type is one of the following:
— a pointer to an object or function (the pointer is said to point to the object or function), or
— a pointer past the end of an object ([expr.add]), or
— the null pointer value for that type, or
— an invalid pointer value.
Now, lets see what happens in the (char *)&a
expression.
Let me not prove that a
is an lvalue denoting the object of type A
, and I will say «the object a
» to refer to this object.
The meaning of the &a
subexpression is covered in [expr.unary.op]/(3.2):
if the operand is an lvalue of type
T
, the resulting expression is a prvalue of type “pointer toT
” whose result is a pointer to the designated object
So, &a
is a prvalue of type A*
with the value «pointer to (the object) a
».
Now, the cast in (char *)&a
is equivalent to reinterpret_cast<char*>(&a)
, which is defined as static_cast<char*>(static_cast<void*>(&a))
([expr.reinterpret.cast]/7).
Cast to void*
doesn't change the pointer value ([conv.ptr]/2):
A prvalue of type “pointer to cv
T
”, whereT
is an object type, can be converted to a prvalue of type “pointer to cvvoid
”. The pointer value ([basic.compound]) is unchanged by this conversion.
i.e. it is still «pointer to (the object) a
».
[expr.static.cast]/13 covers the outer static_cast<char*>(...)
:
A prvalue of type “pointer to cv1
void
” can be converted to a prvalue of type “pointer to cv2T
”, whereT
is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement ofT
, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object a, and there is an object b of typeT
(ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.
There is no object of type char
which is pointer-interconvertible with the object a
([basic.compound]/4):
Two objects a and b are pointer-interconvertible if:
— they are the same object, or
— one is a union object and the other is a non-static data member of that object ([class.union]), or
— one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, any base class subobject of that object ([class.mem]), or
— there exists an object c such that a and c are pointer-interconvertible, and c and b are pointer-interconvertible.
which means that the static_cast<char*>(...)
doesn't change the pointer value and it is the same as in its operand, namely: «pointer to a
».
So, (char *)&a
is a prvalue of type char*
whose value is «pointer to a
». This value is stored into char* ptr
variable. Then, when you try to do pointer arithmetic with such a value, namely ptr + offset
, you step into [expr.add]/6:
For addition or subtraction, if the expressions
P
orQ
have type “pointer to cvT
”, whereT
and the array element type are not similar, the behavior is undefined.
For the purposes of pointer arithmetic, the object a
is considered to be an element of an array A[1]
([basic.compound]/3), so the array element type is A
, the type of the pointer expression P
is «pointer to char
», char
and A
are not similar types (see [conv.qual]/2), so the behavior is undefined.
This question, and the other one about launder
, both seem to me to boil down to interpretation of the last sentence of C++17 [expr.static.cast]/13, which covers what happens for static_cast<T *>
applied to an operand of pointer to unrelated type which is correctly aligned:
A prvalue of type “pointer to cv1
void
” can be converted to a prvalue of type “pointer to cv2T
”,[...]
Otherwise, the pointer value is unchanged by the conversion.
Some posters appear to take this to mean that the result of the cast cannot point to an object of type T
, and consequently that reinterpret_cast
with pointers or references can only be used on pointer-interconvertible types.
But I don't see that as justified, and (this is a reductio ad absurdum argument) that position would also imply:
unsigned char *
or whatever character type supposedly cannot be used to access that byte).offsetof
is useless (and the C++17 changes to it were therefore redundant)It seems like a more sensible interpretation to me that this sentence means the result of the cast points to the same byte in memory as the operand. (As opposed to pointing to some other byte, as can happen for some pointer casts not covered by this sentence). Saying "the value is unchanged" does not mean "the type is unchanged", e.g. we describe conversion from int
to long
as preserving the value.
Also, I guess this may be controversial to some but I am taking as axiomatic that if a pointer's value is the address of an object, then the pointer points to that object, unless the Standard specifically excludes the case.
This is consistent with the text of [basic.compound]/3 which says the converse, i.e. that if a pointer points to an object, then its value is the address of the object.
There doesn't seem to be any other explicit statement defining when a pointer can or cannot be said to point to an object, but basic.compound/3 says that all pointers must be one of four cases (points to an object, points past the end, null, invalid).
Examples of excluded cases include:
std::launder
specifically addresses a situation where there was such language ruling out the use of the un-laundered pointer. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With