I use this malloc style all the time
int *rc = 0;
rc = malloc(sizeof(*rc));
However, it doesn\'t seg fault even though when I call
You are not really dereferencing anything. The argument of sizeof
is not evaluated, unless it is a VLA. It is explicitly allowed by the language to put whatever "garbage" you want as the argument of sizeof
. The language guarantees that it will not evaluate anything, just perform compile-time analysis of the type of the expression. For example, expression sizeof i++
is guaranteed not to change the value of i
.
The only exception from that rule is Variable Length Arrays. The result of sizeof
for VLAs is a run-time value, which means that the argument is evaluated and must be valid.
The sizeof
operator doesn't actually evaluate its operand, it only looks at its type. The type of *rc
is int
, so it's equivalent to sizeof (int)
. This all happens at compile time.
(Also, this is not "inside of malloc".)
That's equivalent to sizeof(type of *rc)
(in other words, sizeof(int)
), not sizeof(data stored at the location pointed to by rc)
. sizeof()
works on types, not values.
sizeof never considers the actual data, just the type, thus there's no need (and it wouldn't make sense) to deference the pointer.
You are not actually dereferencing a pointer, you are asking the compiler for the size of the type rc
points to. In this case sizeof
is resolved at compile time, when there are no pointers.