Silverfrost Forums

Welcome to our forums

Module protected pointer

17 May 2025 10:07 #32113

Often I have an array passed as a dummy argument to a procedure in a module. In order to make that array available to all other procedures in the module a local copy is made as a module variable. This doubles the memory allocation.

For large arrays associating a pointer to the input array would avoid this extra memory allocation. I have been experimenting with this alternative to try and understand the potential pitfalls. This has revealed an issue with module protected pointers.

In the following code since the shared_array has the protected attribute the assigment shared_array(5) = 100 in the main program should generate a compiler error.

Rather a 'twisted' example, since only the subroutines load_array and use_array need to be public in my_mod, in which case FTN95 would correctly reject the code.

module my_mod
  implicit none
  real, pointer, protected :: shared_array(:)
!  real, pointer, private :: shared_array(:)  ! This would be better in this context.

contains

  subroutine load_array(arr)
    real, target, intent(in) :: arr(:)
    shared_array => arr    ! associate pointer to input array
    !shared_array(5) = 100  ! this assigment would correctly change arr despite its intent(in)
  end subroutine load_array

  subroutine use_array()
      print *, shared_array
  end subroutine use_array

end module my_mod

program p
use my_mod
implicit none
real :: a(5) = [1,2,3,4,5]

  call load_array(a)
  
  call use_array()       ! Prints 1,2,3,4,5 via pointer association
  
  shared_array(5) = 100  ! Since shared_array is protected, FTN95 should 
                         ! not permit this assignment (since it's external
                         ! to MY_MOD).
  print*
  call use_array()       ! Prints 1,2,3,4,100 due to line above being permitted.
  
end program p
17 May 2025 10:21 #32115

Ken

Thank you for the bug report. I have logged this for investigation.

17 May 2025 11:34 #32116

This failure has now been fixed for the next release of FTN95.

Please login to reply.