ProgrammingHardIBM · Deloitte pattern
What can be said about this program?
What can be said about this program?
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof(int));
free(p);
free(p);
}- A. The second free(p) is harmless because free() sets its argument to NULL after use
- B. Calling free() twice on the same pointer (a double free) is undefined behavior and can corrupt the heap allocator's metadata
- C. It is legal as long as the first free() call succeeded without error
- D. It always terminates the program immediately with a segmentation fault
Correct answer: B. Calling free() twice on the same pointer (a double free) is undefined behavior and can corrupt the heap allocator's metadata
free() receives p by value, so the caller's p is never modified to NULL. Passing an already-freed pointer to free() again is undefined behavior per 7.22.3.3 and commonly corrupts the allocator's internal bookkeeping.
More C Programming questions
- What is printed? c void modify(int arr[10]) { printf("%lu ", sizeof(arr)); } int main(void) { int a[10]; printf("%lu ", sizeof(a))…
- What is printed? const qualifies what p points to, not p itself. c int x = 5, y = 10; const int p = &x; p = &y; printf("%d", p);
- What is printed? c int a = 10; int p = &a; int q = p; p = NULL; printf("%d", q);
- What is printed? c int f(int n) { if (n == 0) return 0; return n + f(n - 1); } int main(void) { printf("%d", f(4)); }
- What is printed? c int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } int main(void) { printf("%d", fib(6)); }
- What is printed? c int f(int n) { if (n == 0) return 0; printf("%d ", n); if (n % 2 == 0) return f(n / 2); return f(n - 1); } int…