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");- A. It prints done with no issue, since calling free on the same pointer twice is harmless
- B. Undefined behaviour: a double-free, which may corrupt the heap's internal bookkeeping or crash immediately
- C. Compile-time error: free cannot be called twice on the same pointer
- 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
- What happens when this runs? c int arr[10]; for (int i = 0; i <= 10; i++) { arr[i] = i; } printf("done");
- What is printed? c #define CONCAT(a, b) a##b int main(void) { int xy = 100; printf("%d", CONCAT(x, y)); }
- What is printed? c #if defined(FEATUREX) && !defined(FEATUREY) #define MODE 1 #elif !defined(FEATUREX) #define MODE 2 #else #define MODE 3…
- What is printed? c #define INCREMENT(x) x = x + 1 int main(void) { int a = 5, b = 10; if (a > 0) INCREMENT(a); else INCREMENT(b)…
- What happens? c int getDangling(void) { int local = 42; return &local; } int main(void) { int p = getDangling(); printf("%d", p); }
- What happens? (Signed integer overflow.) c #include <limits.h> int main(void) { int x = INTMAX; int y = x + 1; printf("%d", y); }