In a recent post, I realised that when allocating a structure variable, passing the dereferenced pointer deemed a better practice in contrast to passing the structure type to sizeof()
. This is basically because the former is more resilient to code changes than the latter.
Which suggests, that in the following code method 1 is deemed a better practice than method 2.
typedef struct X_ {
int x;
int y;
int z;
} X;
int main() {
X* obj1 = malloc(sizeof(*obj1)); // ----> method 1
X* obj2 = malloc(sizeof(X)); // ----> method 2
return 0;
}
The question is, how valid is it to dereference obj1
in method 1 ? Inside malloc
, obj1
is still unconstructed/uninitialized memory which suggests that dereferencing of obj1
happening inside sizeof()
shouldn't be valid.
Let me make a guess what makes method 1 valid. Is this because since sizeof()
is a compile time operation dereferencing obj1
gets translated into method 2 by the compiler?
Could someone please elaborate the technical validity of this by referring to the relevant C standards?
sizeof
does not evaluate its operand (except for VLAs), iesizeof (42/0)
does not attempt to divide by zero :) – Raychelsizeof
does not evaluate its operand except in the case of VLAs...but still, ifsizeof(*obj1)
is not dereferencingobj1
(which is a pointer toX
) to getX
, then what do we call this? Is it because this is a compile-time operation that it isn't considered "dereferencing"? – Atwatersizeof
only cares about the type. The type of*obj
is the same whatever the value ofobj
is (even ifobj
has an invalid/indeterminate/trap value). The type ofint/int
(42/0
) isint
even if the value has no meaning :-) – Raychel