Does Fortran derived type selection cause automatic release of arrays of elements and pointers?

In Fortran, if I have a selectable array of derived types, each of which consists of a pointer and a selectable array,

type group real, pointer :: object real, allocatable :: objectData(:,:) end type group type(group), allocatable :: myGroup(:) 

I could free all the memory contained in this type just by making one call

 deallocate(myGroup) 

or I need to free arrays in each type first before freeing the derived type:

 do i = 1, size(myGroup) nullify(myGroup(i)%object) deallocate(myGroup(i)%objectData) end do deallocate(myGroup) 

I lean towards option 2 and collapse all the memory until the derived type is freed, if not only so that there is no memory leak, but if option 1 is equivalent, it would be useful for future reference and save me a few lines of code.

+6
source share
2 answers

Only selected components are automatically freed. You must free the pointers yourself.

Be careful, you should free the pointer, not just invalidate. Dropping it simply removes the link to the allocated memory. If you do not free yourself, a memory leak will occur.

+6
source

You know that allocated components are automatically freed , but pointers are not. But for

I could free all the memory contained in this type just by making one call

Answer: yes (with some effort).

If the group type is finalized, then an object of this type terminates when it is freed.

 type group real, pointer :: object real, allocatable :: objectData(:,:) contains final tidy_up end type group 

for the procedure

 subroutine tidy_up(myGroup_array) type(group), intent(inout) :: myGroup_array(:) ! ... deallocate the pointers in the elements of the array end subroutine 

You can use this finalization to take care of the components of the pointer.

Finally, be aware of some of the subtleties . Also note that this slightly reduces your control over whether the pointer is freed (many times you would not want to).

+4
source

Source: https://habr.com/ru/post/983762/


All Articles