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);
}
  1. A. The second free(p) is harmless because free() sets its argument to NULL after use
  2. B. Calling free() twice on the same pointer (a double free) is undefined behavior and can corrupt the heap allocator's metadata
  3. C. It is legal as long as the first free() call succeeded without error
  4. 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

Exams that ask this topic