Alex Rivera | Logout

Is sizeof(*ptr) undefined behavior when pointing to invalid memory?

Asked 2011-10-11T03:48:36.113
39

We all know that dereferencing an null pointer or a pointer to unallocated memory invokes undefined behaviour.

But what is the rule when used within an expression passed to sizeof?

For example:

int *ptr = 0;
int size = sizeof(*ptr);

Is this also undefined?

Edit
Report

1 Answer

17

No. sizeof is an operator, and works on types, not the actual value (which is not evaluated).

To remind you that it's an operator, I suggest you get in the habit of omitting the brackets where practical.

int* ptr = 0;
size_t size = sizeof *ptr;
size = sizeof (int);   /* brackets still required when naming a type */
answered 2011-10-11T03:50:28.953

Your Answer