Free Error / Heap Corruption in Fortran depends on the index that is out of bounds

1.1k views Asked by At

I have a complicated model - to convoluted to post here - and I am trying to debug some strange behavior. I occasionally get free / heap corruption errors at the end of the model run when it is deallocating memory. I can reproduce this behavior in Windows visual fortran and linux gfortran.

I have created a simple test program hello.f90 which reproduces some of the really strange behavior that I see in our application.

Any time the bounds of an array are exceeded - shame on me - it is the programmer's fault, but this behavior makes it really hard to figure out! Depending on the index that is exceeded - first or second of a 2D array - the program will raise a heap corruption error on deallocation or proceed without error when compiled with optimization.

Depending on whether line 23/24 is called, the behavior is totally different!

Obviously the thing to do is compile with check all and get a trace back to the line where the error occurs - but this still seems like bad behavior. I am really curious if someone can at least explain what is happening here!

1

There are 1 answers

5
Vladimir F Героям слава On

If you index an array out of bounds anything can happen. It is an undefined behavior according to the standard. That's why there is the check option you mentioned - to specify what happens at least for the particular implementation. But the program runs slower then.

What really happens is that you probably (you didn't show the actual error messages!) rewrite the internal bookkeeping data structures of the memory allocator (malloc) and the error is then raised when the allocator tries to use that damaged information.