0
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?

2
  • Please look at reducing the spacing of your code as all those blank lines make it hard to follow. Commented Feb 3, 2017 at 9:27
  • 2
    Please do not use uncertain phrases like "it gives memory problems". If it prints some error message, paste it into your question. Read How to Ask Commented Feb 3, 2017 at 9:50

2 Answers 2

2

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.

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

1 Comment

This is just like ABC of fortan90, thank you for remembering it. Sorry for this silly question.
1

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.

Comments

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.