2013-10-16 95 views
2

同樣,Fortran中的指針數組。這麼好,我有一個派生類型:指針數組fortran

type :: t_context_pointer 
    type(t_context),pointer :: p_ctx 
end type t_context_pointer 

當我在主程序:

type(t_context_pointer),allocatable :: tab_ctx_ptr(:) 
type(t_context),allocatable,target :: ctx 
allocate(tab_ctx_ptr(1)) 
allocate(ctx) 
tab_ctx_ptr(1)%p_ctx=>ctx 

它的工作原理。但是,當我用一個函數調用:

type(t_context_pointer),allocatable,target :: tab_ctx_ptr(:) 
allocate(tab_ctx_ptr(n)) 
call alloc_ctx(tab_ctx_ptr,n,1) 

在別處:

subroutine alloc_ctx(tab_ctx_ptr,n,i) 
    integer,intent(in) :: n,i 
    type(t_context_pointer),intent(inout) :: tab_ctx_ptr(n) 

    type(t_context),allocatable,target :: ctx 

    allocate(ctx) 
    tab_ctx_ptr(i)%p_ctx=>ctx 
end subroutine 

它後面的代碼seg_fault。這裏有什麼不對嗎?

回答

4

ctx位於子程序alloc_ctx的範圍內,一旦離開子程序就會被取消分配。稍後訪問(通過指針)會導致段錯誤。

在第一個示例中,您在主程序中分配了ctx,因此其範圍將一直保留到程序結束。

你爲什麼不allocatetab_ctx_ptr(i)%p_ctx直接:

subroutine alloc_ctx(tab_ctx_ptr,n,i) 
    integer,intent(in) :: n,i 
    type(t_context_pointer),intent(inout) :: tab_ctx_ptr(n) 

    allocate(tab_ctx_ptr(i)%p_ctx) 
end subroutine 

至於釋放:你可以使用像這樣的東西釋放了所有的指針(但不包括陣列本身):

subroutine dealloc_ctx(tab_ctx_ptr,n) 
    integer,intent(in) :: n 
    type(t_context_pointer),intent(inout) :: tab_ctx_ptr(n) 
    integer   :: i 

    do i=1,n 
     ! Check whether the current element has an allocated element and 
     ! deallocate if necessary. 
     if (associated(tab_ctx_ptr(i)%p_ctx)) deallocate(tab_ctx_ptr(i)%p_ctx) 
    enddo ! i 
end subroutine 
+0

確定我調用alloc_ctx,編輯! – user2885778

+0

爲什麼這麼做,我的意思不是直接?實際上,這是更復雜的代碼的第一步,它計劃管理多線程分配並確保不同存儲器(如NUMA)中的數據的位置。 – user2885778

+0

最後,如果有自動釋放:如何在C代碼中做? – user2885778