First of all, I've seen this question about C99 and the accepted answer references operand is not evaluated wording in the C99 Standard draft. I'm not sure this answer applies to C++03. There's also this question about C++ that has an accepted answer citing similar wording and also In some contexts, unevaluated operands appear. An unevaluated operand is not evaluated. wording.
I have this code:
int* ptr = 0;
void* buffer = malloc( 10 * sizeof( *ptr ) );
The question is - is there a null pointer dereference (and so UB) inside sizeof()
?
C++03 5.3.3/1 says The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is not evaluated, or a parenthesized type-id.
The linked to answers cite this or similar wording and make use of "is not evaluated" part to deduce there's no UB.
However I cannot find where exactly the Standard links evaluation to having or not having UB in this case.
Does "not evaluating" the expression to which sizeof is applied make it legal to dereference a null or invalid pointer inside sizeof in C++?
if(0) { int*p; *p = 0;}
. – Livessizeof (1/0)
. The standard is unclear on whether dereferencing a null pointer is defined, and consensus seems to be that it should be defined, although subsequently applying the lvalue-to-rvalue conversion would be undefined. – Mesognathoussizeof
the value contained in the referenced object is not accessed, since that operator does not evaluate its operand." C++11 contains a similar specification, but using the more general unevaluated operands instead ofsizeof
. – Peonint* ptr = 0; if (0) *ptr;
The expression*ptr
is not evaluated because of theif
, so there's no undefined behavior. Similarly,sizeof(*ptr)
has no undefined behavior because*ptr
is not evaluated (and the standard explicitlyi says it's not evaluated). I presume you find theif
case unambiguous. Why is thesizeof
case troubling? – Calculation