Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29418 Discussions

Declaring size of array using non-parameters

Joshua_T_
Beginner
1,050 Views

Hello,

I am working on Intel Visual Fortran 11.1 and have a question on declaring an array in a subroutine by defining the size of the array using an argument. The argument can vary each time the subroutine is called, and the compiler does not provide an error, nor a warning.

program main
call suppre(5)
call suppre(6)
stop
end

subroutine suppre(ivar)
integer ivar
real, dimension(ivar) :: array

end subroutine

My question: What are the drawbacks of this practice?

0 Kudos
5 Replies
TimP
Honored Contributor III
1,050 Views

This is called automatic array. In  comparison with allocatable array, it doesn't allow for run time error check and could present stack overflow which may be unnecessarily difficult to diagnose.

It has also been associated with compiler bugs, which you should watch out for when using an old compiler.

0 Kudos
Steven_L_Intel1
Employee
1,050 Views

Tim is right that you can get stack overflow, but array bounds checking is still possible.  For small arrays, there's nothing wrong with doing it this way. If the array is potentially large, then allocatable arrays would be preferable. For example:

subroutine suppre(ivar)
integer ivar
real, allocatable:: array(:)
allocate (array(ivar))

end subroutine

You don't need to deallocate as that will happen automatically.

Just in case anyone is wondering about the use of "dimension" in Joshua's post without bounds, that is indeed not allowed and that source would not compile. But we got the idea.

0 Kudos
Joshua_T_
Beginner
1,050 Views

Hello Tim and Steve,

Thank you for your reply. Aside from stack overflow issues, is the compiler able to allocate memory for the array size without potentially overwriting previously allocated memory for other arrays? I have also updated the code in my previous post, thank you for pointing that out.

Best

0 Kudos
jimdempseyatthecove
Honored Contributor III
1,050 Views

If your code does not write outside the bounds of arrays (assuming bounds checking off), and assuming the heap or stack is not corrupted (presumably by out of bounds writing or invalid interface), and assuming you follow rules about not presenting alias issues on subroutine/function calls, then you will not overwrite previously allocated memory for other arrays.

Jim Dempsey

0 Kudos
jimdempseyatthecove
Honored Contributor III
1,050 Views

Add use of uninitialized or invalid pointers to the list.

Jim Dempsey

0 Kudos
Reply