Intel Visual Fortran allocatable array of fixed length strings - fortran

Running Intel Parallel Studio 2015 and Visual Studio 2012. Fortran 2003 compatibility turned on.
Is there an issue with the following code because it caused a very confusing (for me at least) heap corruption error on my machine and I'm trying to find out if it is something I'm not understanding correctly or a compiler bug.
character(len=200), dimension(:), allocatable :: inFNs
real*8, dimension(:), allocatable :: times
inFNs = (/ "file1.dat", "file2.dat", &
"file3.dat", "file4.dat", &
"file5.dat", "file6.dat" /)
allocate(times(SIZE(inFNs))
!more code below
The code would crash without a stack trace during the allocation of times, and it would tell me that a heap corruption occurred in a window dialog in debug mode.
The way I determined there was an issue with inFNs was because the issue would occur during a later allocate call if I moved the times allocation to be above inFNs.
The error has seemed to go away (knock on wood) by changing the declaration line to:
character(len=:), dimension(:), allocatable :: inFNs
I'm sorting through another issue in my code before I can know for sure.
In Response to Duplicate Question:
This is not a duplicate of the question suggested for so many reasons that I'm truly confused as to the marking. This question deals specifically with the syntax of an allocatable array of character arrays as opposed to alloctable arrays in general. This question deal with a potential compiler bug with Intel Visual Fortran while the other is a question on differences between Intel Fortran and gFortran. This question deals with a silent crash and heap corruption while attempting to use a separate array whereas the other deals with whether or not the array in question is considered allocated after an operation.
Even more to the point the answer in the second question is irrelevant to the issue present in this question as that option being turned on or off doesn't affect the issue presented.
To say these two questions are identical is like saying I was encountering crash with the following code
real :: number
number = 4.d0
and someone asking another question asking why there is an issue with the following
real :: number
number = 4
call add3ToDouble(number)
subroutine add3ToDouble(a)
real*8 :: a
a = a + 3.d0
end subroutine add3ToDouble
and saying the answer to both being "Because ifort defaults to real(kind=4)"

Related

Assignment to unallocated variable [duplicate]

This question already has answers here:
Automatic array allocation upon assignment in Fortran
(2 answers)
Closed 5 years ago.
A line in my code assigns an array to an unallocated array. I thought it was a bug but to my surprise it works just fine.
program test
implicit none
real, allocatable :: x(:,:)
real :: y(2,2)
y = 1.
x = y
print*, x
end program test
How does this work in terms of memory? The = operator here just allocates and assigns at the same time? Why is this possible and why is the compiler not complaining? I am using gfortran 5.4.0.
Since Fortran 2003, allocatable arrays will be automatically allocated (or re-allocated if the shape has changed) at run time. See for instance the Fortran 2003 features of the NAG compiler https://www.nag.com/nagware/np/r61_doc/nag_f2003.pdf or look for "realloc" in the documentation of gfortran https://gcc.gnu.org/onlinedocs/gfortran/Error-and-Warning-Options.html#Error-and-Warning-Options
That is correct, according to Section 7.2.1.3, "Interpretation of intrinsic assignments" of WD 1539-1, paragraph 3.

Increase virtual memory in Fortran

I'm working with a Fortran90 code that works just fine for small arrays. Unfortunately, if the arrays are too large, the program returns an error when allocating the array: severe (41): Insufficient virtual memory.
What I have is:
real*8, allocatable :: M(:,:), C(:,:), K(:,:)
real*8, allocatable :: t(:)
real*8, allocatable :: X(:,:), DX(:,:), D2X(:,:)
real*8, allocatable :: R(:,:)
integer*4 :: nx, nt
integer :: io_stat
...
nx = 15
nt = 6000001
...
allocate(M(nx,nx), C(nx,nx), K(nx,nx),stat=io_stat)
if(io_stat) stop
allocate(t(nt),stat=io_stat)
if(io_stat) stop
allocate(X(nx,nt),DX(nx,nt),D2X(nx,nt),R(nx,nt),stat=io_stat)
if(io_stat) stop
...
The nt parameter is calculated based on the time increment I want to use on the calculations, and this time increment must be very small (1e-9 or smaller) to make the results converge. If nt=600001, the program runs just fine, but the results are not accurate. The problem is: I can't increase the size of the arrays because the program can't allocate all the arrays I'm using (when trying to allocate the DX array, the program already stops). Those are not the only arrays on the code, just the significant (big) arrays.
I'm using Intel(R) Visual Fortran Compiler Professional Edition 11.1 and Microsoft Visual Studio 2008 Version 9.0.21022.8 RTM.
I'm running the code in Windows 8, 64-bit, 16 GB RAM memory.
However, Build -> Configuration Manager is set to Win32 Platform, because I use a library that must run on this platform (I can't change it to a x64 platform).
I would like to know how I can increase the virtual memory, so I can run my code with the proper discretization, i.e., I need more memory to allocate all my arrays. How to do it?
P.S. I runned a similar code on Matlab, and it generated almost 2GB of data (of the X, DX and D2X arrays, which are the results I want). But I have 16GB of ram, so I think memory of the computer is not the problem, but something with the compiler/code. Am I right?
In general you need to ensure:
Your system supports the amount of virtual memory you need.
That you have adequate page file space.
That your process has a large enough quota for virtual memory and working set.

Allocatable character variables in Fortran

My code (stripped down to what I think is relevant for this question) is
PROGRAM test
IMPLICIT NONE
CHARACTER(len=37) input
CHARACTER(len=:), allocatable :: input_trim
WRITE(*,*) 'Filename?'
READ(*,*) input
ALLOCATE(character(len=LEN(TRIM(input))) :: input_trim)
input_trim=trim(input)
.
.
.
END PROGRAM test
It works fine with Intel's Fortran compiler, however gfortran gives me a couple of errors, the first one being in the line saying
CHARACTER(len=:), allocatable :: input_trim
I'm not sure which compiler is 'right' regarding the Fortran standard. Plus I don't know how to achieve what I need in a different way?! I think what I'm doing is more of a workaround anyway. What I need is a character variable containing exactly the filename that was entered with no following spaces.
EDIT: The error is "Syntax error in CHARACTER declaration".
gfortran --version gives me "GNU Fortran (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)"
EDIT 2: You're right regarding the allocate: With ifort, I don't need it. And gfortran crashes before that so maybe it doesn't need the allocate either but I cannot test this at the moment...
This
character (len=:), allocatable :: input_trim
is certainly syntactically correct in Fortran 2003. You don't say what the error that gfortran raises is, so I can't comment on why it doesn't accept the line -- perhaps you have an old version of the compiler installed.
With an up-to-date Fortran compiler (eg Intel Fortran v14.xxx) you don't need to allocate the character variable's size prior to assigning to it, you can simply write
input_trim = trim(input)
Note that
read(*,*) input_trim
won't work.
With Absoft Fortran, this compiles (haven't run with it yet):
character,dimension(:),allocatable::Line_for_IO !Metcalf,Reid,Cohen p. 107, w/mods
if(allocated(Line_for_IO)) deallocate(Line_for_IO)
allocate(Line_for_IO(7*n+40))

Program crash for array copy with ifort

This program crashes with Illegal instruction: 4 on MacOSX Lion and ifort (IFORT) 12.1.0 20111011
program foo
real, pointer :: a(:,:), b(:,:)
allocate(a(5400, 5400))
allocate(b(5400, 3600))
a=1.0
b(:, 1:3600) = a(:, 1:3600)
print *, a
print *, b
deallocate(a)
deallocate(b)
end program
The same program works with gfortran. I don't see any problem. Any ideas ? Unrolling the copy and performing the explicit loop over the columns works in both compilers.
Note that with allocatable instead of pointer I have no problems.
The behavior is the same if the statement is either inside a module or not.
I confirm the same behavior on ifort (IFORT) 12.1.3 20120130.
Apparently, no problem occurs with Linux and ifort 12.1.5
I tried to increase the stack size with the following linking options
ifort -Wl,-stack_size,0x40000000,-stack_addr,0xf0000000 test.f90
but I still get the same error. Increasing ulimit -s to hard same problem.
Edit 2: I did some more debugging and apparently the problem happens when the array splicing operation
b(:, 1:3600) = a(:, 1:3600)
involves a value suspiciously close to 16 M of data.
I am comparing the opcodes produced, but if there is a way to see an intermediate code form that is more communicative, I'd gladly appreciate it.
Your program is correct (though I would prefer allocatable to pointer if you do not need to be able to repoint it). The problem is that ifort by default places all array temporaries on the stack, no matter how large they are. And it seems to need an array temporary for the copy operation you are doing here. To work around ifort's stupid default behavior, always use the -heap-arrays flag when compiling. I.e.
ifort -o test test.f90 -heap-arrays 1600
The number behind -heap-arrays is the threshold where it should begin using the heap. For sizes below this, the stack is used. I chose a pretty low number here - you can probably safely use higher ones. In theory stack arrays are faster, but the difference is usually totally negligible. I wish intel would fix this behavior. Every other compiler has sensible defaults for this setting.
Use "allocatable" instead of "pointer".
real, allocatable :: a(:,:), b(:,:)
Assigning a floating point number to a pointer looks dubious to me.

Stack overflow in Fortran 90

I have written a fairly large program in Fortran 90. It has been working beautifully for quite a while, but today I tried to step it up a notch and increase the problem size (it is a research non-standard FE-solver, if that helps anyone...) Now I get the "stack overflow" error message and naturally the program terminates without giving me anything useful to work with.
The program starts with setting up all relevant arrays and matrices, and after that is done it prints a few lines of stats regarding this to a log-file. Even with my new, larger problem, this works fine (albeit a little slow), but then it fails as the "number crunching" gets going.
What confuses me is that everything at that point is already allocated (and that worked without errors). I'm not entirely sure what the stack is (Wikipedia and several treads here didn't do much since I have only a quite basic knowledge of the "behind the scenes" workings of a computer).
Assume that I for instance have some arrays initialized as:
INTEGER,DIMENSION(64) :: IA
REAL(8),DIMENSION(:,:),ALLOCATABLE :: AA, BB
which after some initialization routines (i.e. read input from file and such) are allocated as (I store some size-integers for easier passing to subroutines in IA of fixed size):
ALLOCATE( AA(N1,N2) , BB(N1,N2) )
IA(1) = N1
IA(2) = N2
This is basically what happens in the initial portion, and so far so good. But when I then call a subroutine
CALL ROUTINE_ONE(AA,BB,IA)
And the routine looks like (nothing fancy):
SUBROUTINE ROUTINE_ONE(AA,BB,IA)
IMPLICIT NONE
INTEGER,DIMENSION(64) :: IA
REAL(8),DIMENSION(IA(1),IA(2)) :: AA, BB
...
do lots of other stuff
...
END SUBROUTINE ROUTINE_ONE
Now I get an error! The output to the screen says:
forrtl: severe (170): Program Exception - stack overflow
However, when I run the program with the debugger it breaks at line 419 in a file called winsig.c (not my file, but probably part of the compiler?). It seems to be part of a routine called sigreterror: and it is the default case that has been invoked, returning the text Invalid signal or error. There is a comment line attached to this which strangely says /* should never happen, but compiler can't tell */ ...?
So I guess my question is, why does this happen and what is actually happening? I thought that as long as I can allocate all the relevant memory I should be fine? Does the call to the subroutine make copies of the arguments, or just pointers to them? If the answer is copies then I can see where the problem might be, and if so: any ideas on how to get around it?
The problem I try to solve is big, but not insane in any way. Standard FE-solvers can handle bigger problems than my current one. I run the program on a Dell PowerEdge 1850 and the OS is Microsoft Server 2008 R2 Enterprise. According to systeminfo at the cmd prompt I have 8GB of physical memory and almost 16GB virtual. As far as I understand the total of all my arrays and matrices should not add up to more than maybe 100MB - about 5.5M integer(4) and 2.5M real(8) (which according to me should be only about 44MB, but let's be fair and add another 50MB for overhead).
I use the Intel Fortran compiler integrated with Microsoft Visual Studio 2008.
Adding some actual source code to clarify a bit
! Update continuum state
CALL UpdateContinuumState(iTask,iArray,posc,dof,dof_k,nodedof,elm,&
bmtrx,detjac,w,mtrlprops,demtrx,dt,stress,strain,effstrain,&
effstress,aa,fi,errmsg)
is the actual call to the routine. Big arrays are posc, bmtrx and aa - all other are at least an order of magnitude smaller (if not more). posc is INTEGER(4) and bmtrx and aa is REAL(8)
SUBROUTINE UpdateContinuumState(iTask,iArray,posc,dof,dof_k,nodedof,elm,bmtrx,&
detjac,w,mtrlprops,demtrx,dt,stress,strain,effstrain,&
effstress,aa,fi,errmsg)
IMPLICIT NONE
!I/O
INTEGER(4) :: iTask, errmsg
INTEGER(4) :: iArray(64)
INTEGER(4),DIMENSION(iArray(15),iArray(15),iArray(5)) :: posc
INTEGER(4),DIMENSION(iArray(22),iArray(21)+1) :: nodedof
INTEGER(4),DIMENSION(iArray(29),iArray(3)+2) :: elm
REAL(8),DIMENSION(iArray(14)) :: dof, dof_k
REAL(8),DIMENSION(iArray(12)*iArray(17),iArray(15)*iArray(5)) :: bmtrx
REAL(8),DIMENSION(iArray(5)*iArray(17)) :: detjac
REAL(8),DIMENSION(iArray(17)) :: w
REAL(8),DIMENSION(iArray(23),iArray(19)) :: mtrlprops
REAL(8),DIMENSION(iArray(8),iArray(8),iArray(23)) :: demtrx
REAL(8) :: dt
REAL(8),DIMENSION(2,iArray(12)*iArray(17)*iArray(5)) :: stress
REAL(8),DIMENSION(iArray(12)*iArray(17)*iArray(5)) :: strain
REAL(8),DIMENSION(2,iArray(17)*iArray(5)) :: effstrain, effstress
REAL(8),DIMENSION(iArray(25)) :: aa
REAL(8),DIMENSION(iArray(14)) :: fi
!Locals
INTEGER(4) :: i, e, mtrl, i1, i2, j1, j2, k1, k2, dim, planetype, elmnodes, &
Nec, elmpnodes, Ndisp, Nstr, Ncomp, Ngpt, Ndofelm
INTEGER(4),DIMENSION(iArray(15)) :: doflist
REAL(8),DIMENSION(iArray(12)*iArray(17),iArray(15)) :: belm
REAL(8),DIMENSION(iArray(17)) :: jelm
REAL(8),DIMENSION(iArray(12)*iArray(17)*iArray(5)) :: dstrain
REAL(8),DIMENSION(iArray(12)*iArray(17)) :: s
REAL(8),DIMENSION(iArray(17)) :: ep, es, dep
REAL(8),DIMENSION(iArray(15),iArray(15)) :: kelm
REAL(8),DIMENSION(iArray(15)) :: felm
dim = iArray(1)
...
And it fails before the last line above.
As per steabert's request, I'll just summarize the conversation in the comments here where it's a bit more visible, even though M.S.B.'s answer already gets right to the nub of the problem.
In technical programming, where procedures often have large local arrays for intermediate computation, this happens a lot. Local variables are generally stored on the stack, which typically (and quite reasonably) a small fraction of overall system memory -- usually of order 10MB or so. When the local variable sizes exceed the stack size, you see exactly the symptoms described here -- a stack overflow occuring after a call to the relevant subroutine but before its first executable statement.
So when this problem happens, the best thing to do is to find the relevant large local variables, and decide what to do. In this case, at least the variables belm and dstrain were getting quite sizable.
Once the variables are located, and you've confirmed that's the problem, there's a few options. As MSB points out, if you can make your arrays smaller, that's one option. Alternatively, you can make the stack size larger; under linux, that's done with ulimit -s [newsize]. That really just postpones the problem, though, and you have to do something different on windows machines.
The other class of ways to avoid this problem is not to put the large data on the stack, but in the rest of memory (the "heap"). You can do that by giving the arrays the save attribute (in C, static); this puts the variable on the heap and thus makes the values persistent between calls. The downside there is that this potentially changes the behavior of the subroutine, and means the subroutine can't be used recursively, and similarly is non-threadsafe (if you're ever in a position where multiple threads will enter the routine simulatneously, they'll each see the same copy of the local varaiable and potentially overwrite each other's results). The upside is that it's easy and very portable -- it should work everywhere. However, this will only work with fixed-size local variables; if the temporary arrays have sizes that depend on the inputs, you can't do this (since there'd no longer be a single variable to save; it could be different size every time the procedure is called).
There are compiler-specific options which put all arrays (or all arrays of larger than some given size) on the heap rather than on the stack; every Fortran compiler I know has an option for this. For ifort, used in the OPs post, it's -heap-arrays in linux, or /heap-arrays for windows. For gfortran, this may actually be the default. This is good for making sure you know what's going on, but it means you have to have different incantations for every compiler to make sure your code works.
Finally, you can make the offending arrays allocatable. Allocated memory goes on the heap; but the variable which points to them is on the stack, so you get the benefits of both approaches. Also, this is completely standard fortran and so totally portable. The downside is that it requires code changes. Also, the allocation process can take nontrivial amounts of time; so if you're going to be calling the routine zillions of times, you may notice this slows things down slightly. (This possible performance regression is easy to fix, though; if you'll be calling it zillions of times with the same size arrays, you can have an optional argument to pass in a pre-allocated local array and use that instead, so that you only allocate/deallocate once).
Allocating/deallocating each time would look like:
SUBROUTINE UpdateContinuumState(iTask,iArray,posc,dof,dof_k,nodedof,elm,bmtrx,&
detjac,w,mtrlprops,demtrx,dt,stress,strain,effstrain,&
effstress,aa,fi,errmsg)
IMPLICIT NONE
!...arguments....
!Locals
!...
REAL(8),DIMENSION(:,:), allocatable :: belm
REAL(8),DIMENSION(:), allocatable :: dstrain
allocate(belm(iArray(12)*iArray(17),iArray(15))
allocate(dstrain(iArray(12)*iArray(17)*iArray(5))
!... work
deallocate(belm)
deallocate(dstrain)
Note that if the subroutine does a lot of work (eg, takes seconds to execute), the overhead from a couple allocate/deallocates should be negligable. If not, and you want to avoid the overhead, using the optional arguments for preallocated worskpace would look something like:
SUBROUTINE UpdateContinuumState(iTask,iArray,posc,dof,dof_k,nodedof,elm,bmtrx,&
detjac,w,mtrlprops,demtrx,dt,stress,strain,effstrain,&
effstress,aa,fi,errmsg,workbelm,workdstrain)
IMPLICIT NONE
!...arguments....
real(8),dimension(:,:), optional, target :: workbelm
real(8),dimension(:), optional, target :: workdstrain
!Locals
!...
REAL(8),DIMENSION(:,:), pointer :: belm
REAL(8),DIMENSION(:), pointer :: dstrain
if (present(workbelm)) then
belm => workbelm
else
allocate(belm(iArray(12)*iArray(17),iArray(15))
endif
if (present(workdstrain)) then
dstrain => workdstrain
else
allocate(dstrain(iArray(12)*iArray(17)*iArray(5))
endif
!... work
if (.not.(present(workbelm))) deallocate(belm)
if (.not.(present(workdstrain))) deallocate(dstrain)
Not all of the memory is created when the program starts. When you call the subroutine the executable is creating the memory that the subroutine needs for local variables. Typically arrays with simple declarations that are local to that subroutine -- neither allocatable, nor pointer -- are allocated on the stack. You could have simply run of of stack space when you reached these declarations. You might have reached a 2GB limit on a 32-bit OS with some array. Sometimes executable statements implicitly create a temporary array on the stack.
Possible solutions: 1) make your arrays smaller (not attractive), 2) make the stack larger), 3) some compilers have options to switch from placing arrays on the stack to dynamically allocating them, similar to the method used for "allocate", 4) identify large arrays and make them allocatable.
The stack is the memory area where the information needed to return from a function, and the information locally defined in a function is stored. So a stack overflow may indicate you have a function that calls another function which in its turn calls another function, etc.
I am not familiar with Fortran (anymore) but another cause might be that those functions declare tons of local variables, or at least variables that need a lot of place.
A last one: the stack is typically rather small, so it's not a priori relevant how much memory the machine has. It should be quite simple to instruct the linker to increase the stack size, at least if you are certain it's just a lack of space, and not a bug in your application.
Edit: do you use recursion in your program? Recursive calls can eat through the stack very quickly.
Edit: have a look at this: (emphasis mine)
On Windows, the stack space to
reserved for the program is set using
the /Fn compiler option, where n is
the number of bytes. Additionally,
the stack reserve size can be
specified through the Visual Studio
IDE which adds the Microsoft Linker
option /STACK: to the linker command
line. To set this, go to Property
Pages>Configuration
Properties>Linker>System>Stack Reserve
Size. There you can specify the stack
size in bytes in either decimal or
C-language notation. If not specified,
the default stack size is 1MB.
The only problem I ran into with a similar test code, is the 2Gb allocation limit for 32-bit compilation. When I exceed it I get an error message on line 419 in winsig.c
Here is the test code
program FortranCon
implicit none
! Variables
INTEGER :: IA(64), S1
REAL(8), DIMENSION(:,:), ALLOCATABLE :: AA, BB
REAL(4) :: S2
INTEGER, PARAMETER :: N = 10960
IA(1)=N
IA(2)=N
ALLOCATE( AA(N,N), BB(N,N) )
AA(1:N,1:N) = 1D0
BB(1:N,1:N) = 2D0
CALL TEST(AA,BB,IA)
S1 = SIZEOF(AA) !Size of each array
S2 = 2*DBLE(S1)/1024/1024 !Total size for 2 arrays in Mb
WRITE (*,100) S2, ' Mb' ! When allocation reached 2Gb then
100 FORMAT (F8.1,A) ! exception occurs in Win32
DEALLOCATE( AA, BB )
end program FortranCon
SUBROUTINE TEST(AA,BB,IA)
IMPLICIT NONE
INTEGER, DIMENSION(64),INTENT(IN) :: IA
REAL(8), DIMENSION(IA(1),IA(2)),INTENT(INOUT) :: AA,BB
... !Do stuff with AA,BB
END SUBROUTINE
When N=10960 it runs ok showing 1832.9 Mb. With N=11960 it crashes. Of course when I compile with x64 it works ok. Each array has 8*N^2 bytes storage. I don't know if it helps but I recommend using the INTENT() keywords for the dummy variables.
Are you using some parallelization? This can be a problem with statically declared arrays. Try all bigger arrays make ALLOCATABLE, otherwise, they will be placed on the stack in autoparallel or OpenMP threads.
For me the issue was the stack reserve size. I went and changed the stack reserved size from 0 to 100000000 and recompiled the code. The code now runs smoothly.