ProgrammingHardTCS NQT · Infosys pattern

What happens when this runs?

What happens when this runs?
void f(int *p) {
    free(p);
    *p = 10;
}
int main(void) {
    int *x = malloc(sizeof(int));
    f(x);
    printf("done");
}
  1. A. It prints done, and *p=10 is safely ignored after freeing
  2. B. Undefined behaviour: writing through p after free(p) is a use-after-free
  3. C. Compile-time error: cannot dereference a pointer immediately after free
  4. D. It always crashes with a segmentation fault

Correct answer: B. Undefined behaviour: writing through p after free(p) is a use-after-free

free(p) releases the memory back to the allocator, which is free to reuse it for anything; p itself is left dangling (still holding the old address, but no longer owning it). Writing *p = 10 afterward is a use-after-free, undefined behaviour — it may silently corrupt unrelated heap data rather than crash, which is part of what makes this bug dangerous.

More C Programming questions

Exams that ask this topic