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

前端 未结 6 1597
我在风中等你
我在风中等你 2020-11-30 04:21

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 pa

6条回答
  •  北海茫月
    2020-11-30 05:11

    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 */
    

提交回复
热议问题