Double Free or Corruption Error

September 18, 2008

A double free or corruption error in a Fortran program means that your program has somehow invoked the free() C runtime function with an invalid pointer. This can happen if it is using dynamic memory allocation or if it is calling free() in C directly somehow.

A common cause of this error is that your code has overwritten memory somewhere due to an out-of-bounds array index. Take the following program, for example:

!! Generates a "double free or corruption" error.
program free
  integer, dimension(:), allocatable :: data
  integer :: i

  do i = 1, 5
     data(i-1) = i
  end do
end program free

After compiling and running we have the following error:

% gfortran -o free free.f90
% ./free
*** glibc detected *** ./free: double free or corruption (out): 0x0000000000607590 ***
======= Backtrace: =========

To check invalid array indexing using the GNU Fortran compiler, compile the program with the -fbounds-check flag and run it again (see gfortran(1) for details). If any array indices are out-of-bounds, you will see an error message like the following:

% gfortran -fbounds-check -o free free.f90
% ./free 
At line 8 of file free.f90
Fortran runtime error: Array reference out of bounds for array 'data', lower bound of dimension 1 exceeded (0 < 1)

This points us directly to line 8 of free.f90 where we see that the first iteration of the loop writes to the invalid element data(-1). Changing the i-1 to i fixes the problem.