ProgrammingHardTCS NQT · Infosys pattern

What happens when this runs?

What happens when this runs?
int *p = (int *)malloc(3 * sizeof(int));
if (p == NULL) {
    return 1;
}
p[0] = 1; p[1] = 2; p[2] = 3;
free(p);
free(p);
printf("done");
  1. A. It prints done with no issue, since calling free on the same pointer twice is harmless
  2. B. Undefined behaviour: a double-free, which may corrupt the heap's internal bookkeeping or crash immediately
  3. C. Compile-time error: free cannot be called twice on the same pointer
  4. D. It reliably prints done the first time and silently ignores the second free call

Correct answer: B. Undefined behaviour: a double-free, which may corrupt the heap's internal bookkeeping or crash immediately

Calling free() twice on the same pointer (a double-free) is undefined behaviour: the allocator's internal free-list/metadata is typically already modified by the first free, and freeing it again corrupts that bookkeeping, which can crash the program immediately, corrupt unrelated heap data, or (worse) appear to work fine until a later, seemingly unrelated failure.

More C Programming questions

Exams that ask this topic