ProgrammingHardIBM · Deloitte pattern

What happens when this runs?

What happens when this runs?
int *p = malloc(10 * sizeof(int));
for (int i = 0; i <= 10; i++) {
    p[i] = i;
}
free(p);
  1. A. It runs fine; malloc always rounds up allocations for safety
  2. B. Undefined behaviour: the loop's i <= 10 writes p[10], one element past the 10 allocated ints
  3. C. Compile-time error: loop bound mismatches allocation size
  4. D. It silently resizes the allocation to fit

Correct answer: B. Undefined behaviour: the loop's i <= 10 writes p[10], one element past the 10 allocated ints

malloc(10 * sizeof(int)) reserves exactly room for 10 ints (indices 0..9); the off-by-one loop condition i <= 10 lets i reach 10, writing p[10], one int past the allocated block — a heap buffer overflow, which is undefined behaviour and can corrupt the allocator's own bookkeeping for adjacent blocks.

More C Programming questions

Exams that ask this topic