5

I've got some test code here that is not acting as I would suspect. I'm using the gfortran compiler.

program test
implicit none

integer, allocatable, dimension(:) :: a
integer, allocatable, dimension(:) :: b

allocate(a(2))
allocate(b(4))

a = 1
b = 2
write(*,*) a
write(*,*) ' '
write(*,*) b
write(*,*) ' '
write(*,*) 'a size before', size(a)

a = b
a = 1

write(*,*) a
write(*,*) ' '
write(*,*) b
write(*,*) ' '
write(*,*) 'a size after', size(a) 
end program test

And I get the following output.

1 1

2 2 2 2

a size before 2

1 1 1 1

2 2 2 2

a size after 4

Why do I not get an error when assigning arrays of different dimensions? Why is the size of a changed?

3
  • 2
    I can reproduce this behaviour with gfortran version 4.8.4 (except that "a size after" is 8, not 4). I have tried to use -fcheck=bounds, but even that didn't work. Looks like a compiler bug to me. Commented Sep 24, 2015 at 4:57
  • Interesting, I'm compiling using gfortran test.f95 -o test.out. Someone should hire me to find bugs if this is the case, I always seem to run into them. Commented Sep 24, 2015 at 5:04
  • 8 is the right answer. Or what am I missing? Commented Sep 24, 2015 at 11:08

1 Answer 1

6

This is a feature called allocation on assignment. When assigning an array to an allocatable array, this gets automatically resized. So after a = b, a is expected to have the size of b.

You can tell the compiler to warn about this via the -Wrealloc-lhs option.

See also this man entry:

-frealloc-lhs

An allocatable left-hand side of an intrinsic assignment is automatically (re)allocated if it is either unallocated or has a different shape. The option is enabled by default except when -std=f95 is given. See also -Wrealloc-lhs.

Also see the related blog entry Doctor, it hurts when I do this by Steve Lionel.

Sign up to request clarification or add additional context in comments.

8 Comments

a(:) and -std=f95 don't seem to prevent the reallocation with gfortran.
Oh wait, it does keep the size of a as 2, just no warning, even with -Wrealloc-lhs
@KierenAnderson Does for me, though to get a runtime error it needs activated bounds checks: -fbounds-check. Without that, size of a remains 2. With bounds checks and -std=f95 it fails.
@KierenAnderson with -std=f95 it does not do a reallocation, so it does not warn about it. But it also does not check the bounds of the arrays, so just does the assignment (wrongly).
@KierenAnderson please correct that in the question
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.