ProgrammingHardIBM · Deloitte pattern

What is the behavior?

What is the behavior?
void f(int n) {
    char buf[n];
    for (int i = 0; i <= n; i++)
        buf[i] = 'a';
}
int main(void) { f(10); }
  1. A. Guaranteed safe since VLAs can always be over-indexed by one
  2. B. Compilation error: VLAs cannot be used in loops
  3. C. Guaranteed to resize buf automatically to fit
  4. D. Undefined behavior: the loop's <= condition writes one byte past the end of the 10-byte variable-length array

Correct answer: D. Undefined behavior: the loop's <= condition writes one byte past the end of the 10-byte variable-length array

buf is a variable-length array of exactly n (10) bytes, valid indices 0..9; the loop's i <= n condition lets i reach 10, writing buf[10], one byte past the end — undefined behavior (stack buffer overflow) regardless of whether buf is a VLA or a fixed-size array.

More C Programming questions

Exams that ask this topic