Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track down a "double free or corruption" error

When I run my (C++) program it crashes with this error.

* glibc detected * ./load: double free or corruption (!prev): 0x0000000000c6ed50 ***

How can I track down the error?

I tried using print (std::cout) statements, without success. Could gdb make this easier?

like image 836
neuromancer Avatar asked May 25 '10 04:05

neuromancer


People also ask

How do you know if something is double free?

Description. Double free errors occur when free() is called more than once with the same memory address as an argument. Calling free() twice on the same value can lead to memory leak.

What is double free or corruption?

The error of double free or corruption in C++ means that our program somehow invokes the free() C++ object with an illegal pointer variable. When we use smart pointers such as shared_ptr, we must check because if we call the function get(), we are directly using the raw pointer.

Which tools can be used to Analyse double free problem in C?

You can use gdb, but I would first try Valgrind. See the quick start guide. Briefly, Valgrind instruments your program so it can detect several kinds of errors in using dynamically allocated memory, such as double frees and writes past the end of allocated blocks of memory (which can corrupt the heap).

How can double free be avoided?

Double Free A simple technique to avoid this type of vulnerability is to always assign NULL to a pointer after it has been freed. Subsequent attempts to free a null pointer will be ignored by most heap managers.


1 Answers

If you're using glibc, you can set the MALLOC_CHECK_ environment variable to 2, this will cause glibc to use an error tolerant version of malloc, which will cause your program to abort at the point where the double free is done.

You can set this from gdb by using the set environment MALLOC_CHECK_ 2 command before running your program; the program should abort, with the free() call visible in the backtrace.

see the man page for malloc() for more information

like image 164
Hasturkun Avatar answered Oct 06 '22 01:10

Hasturkun