简体   繁体   中英

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM