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.
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.
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 heap2. 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-opHow 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.