ProgrammingHardWipro · Cognizant pattern
What happens when this runs?
What happens when this runs?
int arr[10];
for (int i = 0; i <= 10; i++) {
arr[i] = i;
}
printf("done");- A. It prints done; the loop just fills indices 0 through 10 inclusive
- B. Undefined behaviour: the loop condition i <= 10 allows i to reach 10, one past the last valid index (9) of a 10-element array
- C. Compile-time error: the loop bound does not match the array size
- D. It prints done, but only indices 0..9 are actually written since C ignores the extra iteration
Correct answer: B. Undefined behaviour: the loop condition i <= 10 allows i to reach 10, one past the last valid index (9) of a 10-element array
arr has valid indices 0..9; using <= instead of < in the loop condition is a classic off-by-one bug that lets i reach 10, causing arr[10] = 10; to write one element past the end of the array — an out-of-bounds write, which is undefined behaviour (it may silently corrupt adjacent stack memory rather than crashing, which is part of why this bug is so dangerous).
More C Programming questions
- What is printed? c #define CONCAT(a, b) a##b int main(void) { int xy = 100; printf("%d", CONCAT(x, y)); }
- What is printed? c #if defined(FEATUREX) && !defined(FEATUREY) #define MODE 1 #elif !defined(FEATUREX) #define MODE 2 #else #define MODE 3…
- What is printed? c #define INCREMENT(x) x = x + 1 int main(void) { int a = 5, b = 10; if (a > 0) INCREMENT(a); else INCREMENT(b)…
- What happens? c int getDangling(void) { int local = 42; return &local; } int main(void) { int p = getDangling(); printf("%d", p); }
- What happens? (Signed integer overflow.) c #include <limits.h> int main(void) { int x = INTMAX; int y = x + 1; printf("%d", y); }
- What happens? c int p = malloc(sizeof(int)); p = 10; free(p); printf("%d", p);