2

Check this C program:

#include <stdio.h>

int main(void) {
        // your code goes here
        char **p = NULL;

        printf("%d,%d\n", sizeof(*p), sizeof(**p));
        return 0;
}

Executing the above code, the result is:

8,1

Although p is NULL, it doesn't cause program crash in sizeof(*p) and sizeof(**p). How to understand this behavior? Is it assured in spec?

2
  • If you think about what is happening sizeof(*p) is just sizeof (char *) and sizeof(**p) is just sizeof(char) Commented Apr 27, 2016 at 6:35
  • Warning: UB does not guarantee crash, anyway. Commented Apr 27, 2016 at 7:01

4 Answers 4

5

The sizeof operator is evaluated at compile time. Its operand is not evaluated for side effects, so your program is safe. This is guaranteed by the standard 6.5.3.4/2 (emphasis mine):

If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

(Note that there is a special case of variable length arrays, in which case the evaluation takes place in run time, so code de-referencing an invalid pointer to a VLA inside sizeof would not be safe.)

As a side note, the correct format specifier for printf when printing the result of sizeof is %zu (the result of sizeof is type size_t).

Sign up to request clarification or add additional context in comments.

Comments

4

Because sizeof(exp) is a compile time operator, and it does not evaluate expression exp at run-time.

As a result, there is no dereference of NULL pointer at run-time. You just have equivalent machine code of a constant in your printf statement in your final binary.

Comments

3

You know p is a char** so sizeof(*p) == sizeof(char*) - no dereference is actually required.

Same applies to sizeof(**p) - doesn;t have to do any dereference as it can figure out the size at compile time.

Comments

2

The operand of sizeof is unevaluated. In other words, p is never deferenced, therefore it isn't undefined behavior. On a 64-bit system, a pointer will be 8-bytes wide, and a char is always 1 byte, explaining your output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.