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

后端 未结 4 842
灰色年华
灰色年华 2020-12-03 18:28

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

相关标签:
4条回答
  • 2020-12-03 18:32

    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.

    0 讨论(0)
  • 2020-12-03 18:42

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

    0 讨论(0)
  • 2020-12-03 18:42

    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.

    0 讨论(0)
  • 2020-12-03 18:47

    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.

    0 讨论(0)
提交回复
热议问题