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");
}
  1. A. It prints done; all 11 bytes written are part of buffer
  2. 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)
  3. C. Compile-time error: fillBuffer writes out of bounds
  4. 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

Exams that ask this topic