Reputation: 23
module sdata
integer, parameter :: nblock = 2
TYPE block_info
REAL, ALLOCATABLE :: w(:)
END TYPE block_info
TYPE(block_info), TARGET :: block(nblock)
end module sdata
module variable
use sdata
REAL, POINTER :: w(:)
contains
!.............................
subroutine set_current(n)
nullify(w)
allocate(w(10))
w(1:10) => block(n)%w(1:10)
end subroutine set_current
!.............................
end module variable
subroutine make_sth
use variable
use sdata
real,allocatable,dimension(:)::wm,wp,ww
integer n
allocate(wm(5),wp(5),ww(5))
do n = 1,nblock
block(n)%w(1:10) = (/ 1.,2.,3.,4.,5.,6.,7.,8.,9.,10./)
call set_current(n)
wp(1:5) = w(1:5)
wm(1:5) = w(6:10)
ww = wp + wm
do i = 1,5
print*, 'block = ',n,'ww = ',ww(i)
enddo
enddo
end subroutine make_sth
program main
use variable
use sdata
allocate(block(nblock)%w(10))
call make_sth
end program main
Here is my question. For nblock=1 code is perfectly running, however, if I increase nblock ie. to 2 it gives memory problems. How is it possible?
Upvotes: 0
Views: 63
Reputation: 7293
Change
allocate(block(nblock)%w(10))
to
do i = 1, nblock
allocate(block(i)%w(10))
end do
In you current code, you only allocate one element of block
: either block(1)%w(10)
if nblock=1
or block(2)%w(10)
if nblock=2
. With the modification I propose you will allocate an array w
inside of each element of block
.
Upvotes: 1
Reputation: 32451
Let's look at the allocation of the array components of the derived type. In particular the line in the main program
allocate(block(nblock)%w(10))
This is not doing what you think it is, it seems.
What happens here is that the component w
of the element nblock
of block
is allocated. It isn't saying that the nblock
components of block
are all allocated to that size. When nblock
is 1, the effect is the same: no problem.
You need to allocate each element's component individually. Which makes sense, as one would often like each element to have differently sized components, or varying allocation status. There are several approaches for this, but I won't cover those here: there are other questions for that.
Upvotes: 2