Back to questionsWhat happens if you call
MiddleDebuggingCommon
What happens if you call free() twice on the same pointer?
This code frees the same allocation along two paths. AddressSanitizer aborts the program; without it, behaviour is erratic and the heap may be corrupted.
void process(bool early) {
int* p = static_cast<int*>(std::malloc(sizeof(int)));
*p = 42;
if (early)
std::free(p);
// ... more work ...
std::free(p);
}Identify the bug and explain the cause.
Double-free is undefined behaviour: it corrupts the heap metadata stored next to allocations and can crash, silently corrupt data, or create a security vulnerability. AddressSanitizer (-fsanitize=address) detects it instantly at runtime.
- Calling
deleteon a pointer that was already deleted — same UB as double-free - Not zeroing the pointer after free, then checking
if (ptr)before re-freeing — the stale non-null value passes the check - Sharing a raw pointer between two containers, both of which try to free it on destruction
- What is a use-after-free vulnerability and how does it differ from a double-free?
- How does AddressSanitizer detect double-free without hardware support?