1

I don't entirely understand allocation, so this may be a simple problem, but I wrote this Fortran code:

program name
    implicit none
    integer :: A, B
    integer, dimension(:), allocatable :: ARR
    do A = 1, 100
        ARR(A) = A*2
    end do
    do B = 1, 100
        print "(i5)", ARR(A)
    end do
end program name

And it gives me a memory error.

The code was supposed to assign 100 values to the allocatable array, each value being equal to the square of its index number, and then print each value. It instead gave me an error message saying, "Program received signal SIGSEGV: Segmentation fault - invalid memory reference."

1 Answer 1

2

An allocatable object has to be allocated before accessing the elements, i.e.

allocate( ARR(100) )   ! dimensions ARR to 100 elements
do A = 1, 100
   ARR(A) = 2*A

This is the explicit allocation.

There also exists the "allocation of assignment" feature: if the expression on the RHS (right-hand side) is an array of the same rank (and of a compatible type), then the allocatable array on the LHS is automatically allocated with the size of the RHS.

In your particular case the RHS could be an array constructor [...] containing an implied-do loop:

ARR = [ (A*2, A=1,100) ]   ! ARR is automatically allocated without
                           ! needing allocate( ARR(100) ) first

Note that the allocation on assignment only works if the LHS is the full array and not an array section:

ARR(:) = [ (A*2, A=1,100) ]   ! doesn't work if ARR is not already allocated

Note also that the "allocation on assignment" feature is also a "reallocation on assignment" feature: if the LHS allocatable array is already allocated with a size that differs from the size of the RHS, then it is deallocated first and reallocated with the new size. This for instance makes possible to build the array by iteratively appending one element at a time (the array has to be initially allocated to an empty array):

allocate( ARR(0) ) ! or ARR = [integer::]
do A = 1, 100
   ARR = [ ARR, A*2 ]
end do

This approach is highly inefficient in terms of performance, though.

Not the answer you're looking for? Browse other questions tagged or ask your own question.