Deallocate causes program to stop without error message

187 Views Asked by At

I'm learning Fortran with the book Fortran 90 for scientists and engineers by Brian Hahn. In chapter 9 about arrays, pages 131/132, he gives the following code as an example of dynamic arrays

Program Chap_9_Allocatable_Array

Implicit none

! Variables
Real, dimension(:), Allocatable    :: X, OldX
Real                                  A
Integer                               IO, N, i

! Body of Chap_9_Allocatable_Array
Allocate( X(0) )                   !Size zero to sart with?
N = 0
Open(1, File = 'Data.txt')

Do
    Read(1, *, IOStat = IO) A
    If (IO < 0) Exit
    N = N + 1
    Allocate( OldX( Size(X) ) )
    OldX = X                       !Entire array can be assigned
    Deallocate( X )
    Allocate( X(N) )
    X = OldX
    X(N) = A
    Deallocate( OldX )
End do

Print *, (X(i), i = 1, N)

End program Chap_9_Allocatable_Array

I have implemented this program in Visual Studio Community 2019 with the Intel Visual Fortran Compiler. The purpose of this program as he explains is

The following program extract shows how to use allocatable arrays, as these beasts are called, to read an unknown amount of data, which unfortunately must be supplied one item per line because of the way READ works.

I found an interesting error. The file data.txt consists of 100 random numbers, 1 per row. When I try to run it, it just seems to stall for a couple of seconds and then the console simply prints the

Press any key to continue.

prompt, without an error message. I have inserted some debug prints and determined that the program runs the do cycle between 3 to 8 times before stopping. I have not been able to determine the reason. If I then change the data.txt file to only be 3 numbers long, the program runs as intended. With the debug prints, I have pinned the error to being the

Deallocate( X )

line. If I debug the program in Visual Studio I just get the following message:

Chap_9_Allocatable_Array.exe has triggered a breakpoint.

There have been a few minor errors in the book. Just in this example, the author seems to have forgotten to declare i, which caused a compile error. However, as I'm only beggining to understand arrays, I don't know what else to try. Any ideas?

0

There are 0 best solutions below