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

pointers as arguments - woe is me (Intel Fortran 10.0, Linux, x64)

fattyboomsticks
Beginner
803 Views
Allocating an array within a subroutine and then associating a pointer argument (of the subroutine) to the array is giving unexpected results. Upon leaving the subroutine, the pointer is associated but the memory that it should be pointing to appears to have been deallocated.

A simple example. Suppose the subroutine test1 resides in a MODULE somehwere:-

SUBROUTINE test1(array1)
INTEGER, DIMENSION(:), POINTER :: array1

INTEGER, DIMENSION(:), ALLOCATABLE, TARGET :: test_array
INTEGER i

ALLOCATE(test_array(1:2))

DO i = 1, 2
test_array(i) = i
END DO

array=>test_array

DO i = 1, 2
PRINT *, array1(i) !This gives the expected result i.e. "1, 2"
END DO

END SUBROUTINE test1

Now try calling test1() in the program main, as follows:

PROGRAM test
USE test_module !Contains test1()
IMPLICIT NONE

INTEGER, DIMENSION(:), POINTER :: array
INTEGER i

CALL test1(array1 = array)

IF(ASSOCIATED(array)) THEN
PRINT *, "ASSOCIATED" !Prints 'ASSOCIATED', as expected...
ELSE
PRINT *, "UNASSOCIATED"
END IF

DO i = 1, 2
PRINT *, array(i) !...however this prints seemingly random values!
END DO
END PROGRAM test

Is there some catch about using a pointer argument that I have missed?

Thanks for any help!
0 Kudos
4 Replies
TimP
Honored Contributor III
803 Views
Automatic deallocation is required by the f95 and 03 standards, when leaving the subroutine where ALLOCATE is executed. Prior to that, the situation was undefined.
0 Kudos
fattyboomsticks
Beginner
803 Views
Thanks for your prompt response.
0 Kudos
jimdempseyatthecove
Honored Contributor III
803 Views

You could perform the allocation on the pointer

INTEGER, DIMENSION(:), POINTER :: array1
...
allocate(array1(n))

Then it will persist through the return

Jim Dempsey

0 Kudos
Steven_L_Intel1
Employee
803 Views
You want to put the SAVE attribute on the ALLOCATABLE array. This will preserve its value when the routine exits. You may want to add an IF (ALLOCATED()) test in the routine to make sure you don't accidentally reallocate it.
0 Kudos
Reply