Why doesn't my program undo the error when dereferencing a NULL pointer inside malloc?

I use this malloc style all the time
int *rc = 0; rc = malloc(sizeof(*rc));

However, this does not happen, even if when calling sizeof(*rc) I assume that rc==0 , and I dereference the NULL pointer.

+6
source share
4 answers

You really are not looking for anything. sizeof not evaluated if it is not a VLA. The language is explicitly permitted by the language to host any "garbage" you want as an argument to sizeof . The language guarantees that it will not evaluate anything, just do an analysis of the compilation time of the type of expression. For example, the expression sizeof i++ guaranteed not to change the value of i .

The only exception to this rule is variable length arrays. The sizeof for the VLA is a run-time value, which means that the argument is evaluated and must be valid.

+19
source

The sizeof operator does not actually evaluate its operand; it only looks at its type. The *rc type is int , so it is equivalent to sizeof (int) . This happens at compile time.

(Also, this is not "inside malloc.")

+8
source

You are not actually looking for a pointer; you are asking the compiler to specify a size of type rc . In this case, sizeof allowed at compile time when there are no pointers.

+4
source

This is equivalent to sizeof(type of *rc) (in other words, sizeof(int) ), not sizeof(data stored at the location pointed to by rc) . sizeof() works with types, not values.

sizeof never considers the actual data, just a type, so there is no need (and it does not make sense) to refer to a pointer.

+3
source

All Articles