Invalid Pointer in Fortran

Check your indices when you write on allocatable arrays

First, I really enjoy working with Fortran as a language. The relative simplicity and close to the metal of this language makes it very easy to write insanely efficient code. Fortran is old but also very modern thanks to regular updates of the standard and its very good support by Intel and GCC. One beautiful thing is that you can keep coding like it was in the 90's, very performance oriented and use just a bit of the new features to manage more easily large amount of data. That is, you can create user defined data types to store stuff:

TYPE MySmallStuff
    INTEGER          :: foo   !< The ultimate foo value
    DOUBLE PRECISION,ALLOCATABLE:: values(:)      !< Some values 

TYPE MyBigStuff
    INTEGER          :: nsmalls
    TYPE(MySmallStuff),ALLOCATABLE:: smalls(:)   

What you have here, one base derived data type, MyBigStuff storing a series of MySmallStuff. In my case, it was the configuration of an optimizer storing a series of parameters to be optimized. The values for each parameter was the value at each iteration of each parameter.

When using my code, I had sometimes the following error:

free(): invalid pointer

Program received signal SIGABRT: Process abort signal.

Backtrace for this error:
#0  0x7fa42a9ee2ed in ???
#1  0x7fa42a9ed503 in ???
#2  0x7fa42a282fcf in ???
#3  0x7fa42a282f47 in ???
#4  0x7fa42a2848b0 in ???

What was interesting is that the error was when trying to deallocate (automatically or not) on of the elements in smalls. The reason was not at all what I expected: I started to write at indice 0 in values of MySmallStuff.

After writing the historical values, I was able to print them correctly, iterating on values(1:nvalues) but freeing the same allocatable I was able to read values from was crashing with the invalid pointer. This was because I allocated MyBigStuff%smalls(2), then for each smalls, I allocated the values. When writing for one of them at values(0), I destroyed part of the pointer information. This is what triggered the error. Normally I run my code with boundary checks on the arrays, but not in this particular case. I suppose the boundary checks would have caught the off-by-one error...

I was taken off guard because normally, errors in Fortran are pretty obvious, this one took me nearly one hour to pinpoint.

Fluid Phase Equilibria, Chemical Properties & Databases
Back to Top