(j3.2006) C_LOC and deallocating a pointer

Bill Long longb
Thu Jun 16 17:21:22 EDT 2016


In general, if you try to deallocate a pointer, the memory involved should have been allocated by allocation of a pointer.   Thus, for example, if the target of the pointer is a explicit-shape array or is allocatable, there is an error. That is all pretty clear if you stay in the Fortran domain.  However, what about cases like this:


type(C_PTR) :: px
integer,pointer :: p(:), q(:), r(:)
?
! Part A - somehow allocate memory for p
?
q => p
px = C_LOC(q)

! Part B - Pass px to a C function that uses it somehow

call c_f_pointer (px, r(100))
deallocate(r)

========

Case 1:  Is this ever legal, independent of how P was allocated in Part A?  The variable px contains only the C address of the target - all the Fortran ?pointer? information is lost (with typical implementations) at this point. So the deallocation of r does not have sufficient information to determine whether the deallocate should generate an error. 

Case 2: In part A the memory is allocated by malloc() in a C function. How would the deallocate know that the C allocation was for 100 elements?

Case 3: The declaration for P is, instead, allocatable,target, and the memory in Part A is allocated by a Fortran ALLOCATE statement. In this case the runtime should raise an error, but is there sufficient information to determine that?  Unfortunately, compilers are not in agreement about this case. 

Cheers,
Bill





Bill Long                                                                       longb at cray.com
Fortran Technical Support  &                                  voice:  651-605-9024
Bioinformatics Software Development                     fax:  651-605-9142
Cray Inc./ Cray Plaza, Suite 210/ 380 Jackson St./ St. Paul, MN 55101





More information about the J3 mailing list