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);- A. It runs fine; malloc always rounds up allocations for safety
- B. Undefined behaviour: the loop's i <= 10 writes p[10], one element past the 10 allocated ints
- C. Compile-time error: loop bound mismatches allocation size
- 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
- Assume 32-bit int. What is printed? c int a = 6; int b = a++ 2; printf("%d %d", a, b);
- What is printed? c #define MAXSIZE 100 #if MAXSIZE > 50 const char label = "large"; #else const char label = "small"; #endif printf("%s"…
- Assume 32-bit int. What is printed? c int x = 10; int p = &x; p += 5; p = 2; printf("%d", x);
- What happens when this runs? c int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } int main(void) {…
- Assume 32-bit int. What is printed? c int arr[3] = {1, 2, 3}; int total = 0; int i; for (i = 0; i < 3; i++) total = total + arr[i]…
- Assume a 64-bit LP64 ABI. What is printed? c int createZeroed(int n) { int arr = calloc(n, sizeof(int)); return arr; } int main(void) {…