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");
}- A. Prints null, safely
- B. Undefined behaviour: p is an uninitialised local pointer with an indeterminate value, so the comparison p != NULL is itself unreliable
- C. Prints 0
- 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
- Assume a 64-bit LP64 ABI. What is printed? c struct Inventory { char name[16]; int quantity; double price; }; void restock(struct…
- Assume 32-bit int. What is printed? c #define SWAP(a, b, type) do { type t = a; a = b; b = t; } while (0) int main(void) { int x = 1, y =…
- Assume 32-bit int. What is printed? c int x = 5, y = 3; int result = x++ - ++y; printf("%d %d %d", x, y, result);
- What is printed? c int main(void) { int a = 1, b = 2, c = 3, d = 4; int result = (a < b) ? ((c < d) ? 1 : 2) : ((c < d) ? 3 : 4)…
- What is printed? c int main(void) { int scores[5] = {85, 92, 78, 95, 88}; int max = scores[0]; for (int i = 1; i < 5; i++) { if (scores[i]…
- Assume a 64-bit LP64 ABI. What is printed? c struct Pair { int first; int second; }; struct Pair makePair(int a, int b) { return (struct…