TryBugHunt

free(): invalid pointer / double free

free(): invalid pointer / double free in C++ means your C++ program attempted to deallocate memory using delete or free() that was either already freed, was not allocated on the heap, or whose memory management header was corrupted.

C++Pattern: Scope and closure bugs

How do I fix free(): invalid pointer / double free?

To fix free(): invalid pointer / double free in C++, locate the line causing the error and check the values right before it runs. Most occurrences happen because of calling delete on a stack variable. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.

1. Inspect bounds & typesPrint or inspect collection sizes and verify variables are not empty or None/undefined.
2. Guard with safe accessUse optional chaining (?.), dictionary get(), or guard conditions before dereferencing.
3. Trace upstream originsFind where the value was instantiated or returned rather than only patching the symptom.

What does free(): invalid pointer / double free mean?

The C/C++ memory allocator (glibc or jemalloc) tracks heap chunk allocations. When free() or delete is passed a pointer that doesn't point to the start of an active heap allocation block, the allocator aborts the process to prevent memory corruption attacks.

Why does free(): invalid pointer / double free happen?

1. Calling delete on a stack variable

Stack variables are automatically cleaned up when they exit scope. Deleting them corrupts the heap metadata.

Breaks

int x = 42;
int* ptr = &x;
delete ptr; // crashes with free(): invalid pointer!

Works

int* ptr = new int(42);
delete ptr; // correctly allocated on heap

2. Double free: deleting the same pointer twice

After delete ptr, the memory is returned to the pool. A second delete ptr invokes undefined behavior and triggers an abort.

Breaks

delete ptr;
delete ptr; // double free!

Works

delete ptr;
ptr = nullptr; // deleting nullptr is a safe no-op

How to find it in your own code

Prefer modern RAII smart pointers (std::unique_ptr and std::make_shared) over raw 'new' and 'delete'. If raw pointers are necessary, set the pointer to nullptr immediately after delete.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.