ProgrammingHardWipro · Cognizant pattern
What happens when this runs?
What happens when this runs?
void fillBuffer(char *buf, int size) {
for (int i = 0; i <= size; i++) {
buf[i] = 'A';
}
}
int main(void) {
char buffer[10];
fillBuffer(buffer, 10);
printf("done");
}- A. It prints done; all 11 bytes written are part of buffer
- B. Undefined behaviour: the loop condition i <= size lets i reach 10, writing buffer[10], one byte past the 10-byte buffer's valid range (0..9)
- C. Compile-time error: fillBuffer writes out of bounds
- D. It silently truncates the write at index 9
Correct answer: B. Undefined behaviour: the loop condition i <= size lets i reach 10, writing buffer[10], one byte past the 10-byte buffer's valid range (0..9)
buffer has valid indices 0..9; the off-by-one loop condition i <= size (should be i < size) lets the loop run with i=10 too, writing buf[10], which is one byte beyond the array's allocated storage — an out-of-bounds write and undefined behaviour, potentially corrupting adjacent stack memory (a classic, dangerous off-by-one bug).
More C Programming questions
- What happens when this runs? c int a = 5; int b = a++ + a++ + a++; printf("%d %d", a, b);
- What happens when this runs? c struct Point { int x, y; }; struct Point p = malloc(sizeof(struct Point)); printf("%d", p->x);
- What happens when this runs? c char concat(const char a, const char b) { char result[100]; strcpy(result, a); strcat(result, b); return…
- What is printed? c int a = 5, b = 2, c = 3; int result = a > b > c; printf("%d", result);
- What is printed? c int a = 1, b = 2, c = 3; int result = a == 1 && b == 2 || c == 100; printf("%d", result);
- What is printed? c int a = 4; int b = ~a + 1; printf("%d %d", b, -a);