C Programming · Interview question

What is use-after-free and why is it so dangerous?

A strong answer

It's reading or writing through a pointer after the memory it references has been freed. The danger is that the allocator may have already handed that block to a different malloc, so your stale pointer now aliases live, unrelated data, writes corrupt it, reads leak it. The behavior is undefined and often non-deterministic: it might work in testing and fail in production when allocation patterns differ. It's also a premier security vulnerability class, attackers deliberately groom the heap so the freed block gets reused by an object they control, turning a use-after-free into code execution. Defenses: set pointers to NULL immediately after freeing (turns the bug into a deterministic NULL deref), establish clear ownership of who frees what, and run AddressSanitizer, which instruments allocations to flag the access precisely.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Dynamic Memory: malloc & free

Sizing memory at runtime with malloc/calloc/realloc, and the discipline of free that prevents leaks, double-frees, and use-after-free bugs.

More Dynamic Memory: malloc & free questions

Browse all 472 interview questions
What is use-after-free and why is it so dangerous? | EmbeddedPrep.io