CallMeNorm
CallMeNorm

Reputation: 2605

Why doesn't my program seg fault when I dereference a NULL pointer inside of malloc?

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 sizeof(*rc) I assume that rc==0, and I am dereferencing a NULL pointer.

Upvotes: 12

Views: 1022

Answers (4)

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

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.

Upvotes: 27

imreal
imreal

Reputation: 10378

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.

Upvotes: 4

Corbin
Corbin

Reputation: 33467

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.

Upvotes: 3

melpomene
melpomene

Reputation: 85897

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".)

Upvotes: 9

Related Questions