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); }- A. Guaranteed safe since VLAs can always be over-indexed by one
- B. Compilation error: VLAs cannot be used in loops
- C. Guaranteed to resize buf automatically to fit
- 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
- What is printed? c // file1.c int x = 10; // file2.c (same program, separate translation unit) extern int x; void show(void) {…
- What is printed? c int x = 100; void f(void) { int x = 5; { int x = 1; printf("%d ", x); } printf("%d ", x); } int main(void) { f()…
- What is printed? c int x = 5; int f(void) { int x = x + 1; return x; } int main(void) { printf("%d", f()); }
- What is printed? c int f(void) { static int x; return x++; } int main(void) { printf("%d %d %d", f(), f(), f()); }
- What is printed? c static int helper(int n) { return n 2; } int main(void) { printf("%d", helper(5)); }
- What is printed? c void f(void) { static int x = 0; x += 10; printf("%d ", x); } int main(void) { for (int i = 0; i < 3; i++) f(); }