Passed array with more elements that expected in subroutine

无人久伴 提交于 2021-02-08 05:14:30

问题


I have a subroutine in a shared library:

SUBROUTINE DLLSUBR(ARR)
   IMPLICIT NONE
   INTEGER, PARAMETER :: N = 2
   REAL ARR(0:N)
   arr(0) = 0
   arr(1) = 1
   arr(2) = 2
END

And let's assume I will call it from executable by:

REAL ARR(0:3)
CALL DLLSUBR(ARR)

Note: The code happily compiles and runs (DLLSUBR is inside a module) without any warning or error in Debug + /check:all option switched on.

Could this lead to memory corruption or some weird behaviour? Where I can find info about passing array with different size in the Fortran specification?


回答1:


It is actually allowed for explicit shape arrays by the rules of sequence association, if you make the dummy argument element count to be smaller or equal. It is prohibited when the subroutine expects more elements then it gets.

The explicit shape arrays often require the arguments to be passed by a copy. This happens when the compiler cannot prove the array is contiguous (a pointer or an assumed shape array dummy argument). If smaller number of elements was passed, the subroutine could then access some garbage after the copy of the portion of the array.

In your case everything will be OK, because you are passing more to a subroutine expecting less.

Fortran 2008 12.5.2.11.4:

4 An actual argument that represents an element sequence and corresponds to a dummy argument that is an array is sequence associated with the dummy argument if the dummy argument is an explicit-shape or assumed-size array. The rank and shape of the actual argument need not agree with the rank and shape of the dummy argument, but the number of elements in the dummy argument shall not exceed the number of elements in the element sequence of the actual argument. If the dummy argument is assumed-size, the number of elements in the dummy argument is exactly the number of elements in the element sequence.



来源:https://stackoverflow.com/questions/21456642/passed-array-with-more-elements-that-expected-in-subroutine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!