ProgrammingHardTCS NQT · Infosys pattern

What happens when this runs?

What happens when this runs?
struct Point { int x, y; };
struct Point *p = malloc(sizeof(struct Point));
printf("%d", p->x);
  1. A. 0, since malloc zero-initialises memory
  2. B. Undefined behaviour: malloc does not initialise memory, so p->x holds an indeterminate value
  3. C. Compile-time error: p->x is used before being assigned
  4. D. Always the same garbage value across all runs and systems

Correct answer: B. Undefined behaviour: malloc does not initialise memory, so p->x holds an indeterminate value

malloc only reserves raw memory; it does NOT clear or initialise it (unlike calloc, which does zero-fill). Reading p->x before explicitly assigning it is reading an indeterminate value, which is undefined behaviour — it is a common and dangerous mistake to assume malloc'd memory starts at zero.

More C Programming questions

Exams that ask this topic