ProgrammingHardTCS NQT · Infosys pattern

What happens when this runs?

What happens when this runs?
int *p;
if (p != NULL) {
    printf("%d", *p);
} else {
    printf("null");
}
  1. A. Prints null, safely
  2. B. Undefined behaviour: p is an uninitialised local pointer with an indeterminate value, so the comparison p != NULL is itself unreliable
  3. C. Prints 0
  4. D. Compile-time error: p must be initialised

Correct answer: B. Undefined behaviour: p is an uninitialised local pointer with an indeterminate value, so the comparison p != NULL is itself unreliable

p is a local pointer with no initializer, holding an indeterminate value — it is NOT guaranteed to be NULL (only static-duration pointers are zero-initialised by default). Even just reading p's indeterminate value for the comparison p != NULL is undefined behaviour here, so neither branch's outcome can be relied upon.

More C Programming questions

Exams that ask this topic