ProgrammingHardWipro · Cognizant pattern

What happens when this runs?

What happens when this runs?
int a[5] = {1, 2, 3, 4, 5};
a[5] = 100;
printf("%d", a[5]);
  1. A. 100, since C automatically grows arrays
  2. B. Undefined behaviour: a[5] is one past the valid index range of a 5-element array
  3. C. Compile-time error: array index 5 is out of bounds
  4. D. 0, since out-of-bounds writes are silently ignored

Correct answer: B. Undefined behaviour: a[5] is one past the valid index range of a 5-element array

a has valid indices 0..4; a[5] accesses memory outside the array entirely. C performs no bounds checking, so both the write and the read are undefined behaviour — it may silently 'work' by corrupting adjacent memory, or crash, or do something else entirely, with no guarantee either way.

More C Programming questions

Exams that ask this topic