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.
If the program dereferences the null pointer, it can cause a segmentation fault or other undefined behavior, which can lead to a crash.
Dereferencing a null pointer always results in undefined behavior and can cause crashes. If the compiler finds a pointer dereference, it treats that pointer as nonnull. As a result, the optimizer may remove null equality checks for dereferenced pointers.
It is usually the next-block pointer inside the malloc that is changed by your heap corruption to an invalid address, so that when you call malloc an invalid pointer gets dereferenced and you get a segmentation fault.
In practice, segfaults are almost always due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or (in C programs) accidentally using a variable's value as an address (see the scanf example below).
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".)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With