How can I avoid a stack overflow when Fortran prod

2019-01-20 18:20发布

问题:

I have some Fortran code that calls RESHAPE to reorder a matrix such that the dimension that I am now about to loop over becomes the first varying dimension (Column-major order in Fortran).

This has nothing to do with C/Fortran interoperability.

Now the matrix is rather large and when I call the RESHAPE function I get a seg fault which I am very confident is a stack overflow. I know this because I can compile my code in ifort with -heap-arrays and the problem disappears.

I do not want to modify the stack-size. This code needs to be portable for any computer without the user having to concern himself with stack-size.

Is there someway I can get this call of the RESHAPE function to use the heap and not the stack for its internal memory use.

Worst case I will have to 'roll my own' RESHAPE function for this instance but I wish there was a better way.

回答1:

The Fortran standard does not speak about stack and heap at all, that is an implementation detail. In which part of memory something is placed and whether there are any limits is implementation defined.

Therefore it is impossible to control the stack or heap behaviour from the Fortran code itself. The compiler must be instructed by other means if you want to specify this and the compiler options are used for that. Intel Fortran uses stack by default and has the -heap-arrays n option (n is the limit in kB), gfortran is slightly different and has the opposite -fstack-arrays option (included in -Ofast, but can be disabled).

This is valid for all kinds of temporaries and automatic arrays.