ProgrammingHardTCS NQT · Infosys pattern

What happens when this runs?

What happens when this runs?
int *p = malloc(sizeof(int));
free(p);
printf("%d", *p);
  1. A. It reliably prints whatever value was last stored there before free
  2. B. Undefined behaviour: use-after-free, p is now a dangling pointer
  3. C. Compile-time error: cannot use p after free(p)
  4. D. It always prints 0

Correct answer: B. Undefined behaviour: use-after-free, p is now a dangling pointer

free(p) returns the memory to the allocator, which may reuse, overwrite, or unmap it at any time; p itself still holds the old address (it is not automatically nulled). Dereferencing it afterward is a classic use-after-free, which is undefined behaviour — the value might coincidentally look unchanged, but relying on that is incorrect and dangerous.

More C Programming questions

Exams that ask this topic