The following test code constructs a basic binary tree out of an unsorted array of integers, and outputs the tree in sorted order. It runs without error with FTN95-32 bit, as well as with other compilers.
The 8.65 FTN95 compiler, used with /64 alone or /64 with other options, produces EXEs that abort with access violations or 'reference through unset Fortran pointer'.
! For each node, the convention is:
! If %v == 0, the node is not yet allocated and has no value or branches
! if %l is unassociated, there is no left branch
! if %l is unassociated, there is no right branch
! Duplicate values are rejected
!
module BinaryTree
type node
type(node), pointer :: l => NULL(), r => NULL()
integer :: v = 0
end type
integer, parameter :: NVM = 60
type(node), target,save :: nodes(NVM)
integer :: nnodes = 0
contains
subroutine insert(anode,val,found,nnod)
implicit none
type(node), intent(in),target :: anode(*)
integer, intent(in) :: val
integer, intent(in out) :: nnod
logical, intent(out) :: found
type(node), pointer :: nd
found = .false.; nd => anode(1)
do
if(nd%v == 0)then ! Do not move this IF block since
nd%v = val ! nd%l, nd%v should not be referenced
nnod = nnod+1 ! unless nd%v is not zero
return
else if(val < nd%v)then
if(.not.associated(nd%l))then
nnod = nnod+1
nd%l => anode(nnod)
nd%l%v = val
return
endif
nd => nd%l
else if(val > nd%v)then
if(.not.associated(nd%r))then
nnod = nnod+1
nd%r => anode(nnod)
nd%r%v = val
return
endif
nd => nd%r
else if(val == nd%v)then
found = .true.
return
endif
end do
stop 'Should not have reached this line at end of Subroutine INSERT!'
end subroutine insert
recursive subroutine ptree(base)
type(node) :: base
if(base%v == 0)return
if(associated(base%l))call ptree(base%l);
write(*,'(i5)',advance='no')base%v
if(associated(base%r))call ptree(base%r);
return
end subroutine
end module
program tst
use BinaryTree
implicit none
integer, parameter :: NX = 15
integer, dimension(NX) :: vals = &
[172, 97, 2,166,189, 91, 27, 23,156, 64,113, 29,173,172,114]
type(node), pointer :: base
logical :: found
integer :: i
!
base => nodes(1)
nullify(base%l); nullify(base%r); base%v = 0
nnodes = 0
print '(A,/,15i5,/)','Unsorted array:',vals
do i = 1,NX
call insert(nodes,vals(i),found,nnodes)
if(found)print *,'Value ',vals(i),' already in tree, not inserted'
end do
print *
print *,'Sorted array, duplicates removed:'
call ptree(nodes(1))
end program