[patch, fortran] Fix pointers not escaping via C_PTR
Thomas Koenig
tkoenig@netcologne.de
Sat Mar 2 11:23:00 GMT 2019
Hi Steve,
> On Thu, Feb 28, 2019 at 09:14:48PM +0100, Thomas Koenig wrote:
>>
>> the attached patch fixes a wrong-code bug for gfortran where pointers
>> were not marked as escaping. A C_PTR can be stashed away and reused
>> later (at least as long as the variable it points to remains active).
>>
>> This is not a regression, but IMHO a bad wrong-code bug. The chances
>> of this patch introducing regressions are really, really low.
>>
>> Regression-tested. OK for trunk?
>>
>
> Is this a wrong code bug or a clever user wandering off into
> undefined behavior?
>
>> subroutine init()
>> use, intrinsic :: iso_c_binding
>> implicit none
>> integer(c_int), pointer :: a
>> allocate(a)
>> call save_cptr(c_loc(a))
>> a = 100
>> end subroutine init
>
> Of particular note, 'a' is an unsaved local variable. When init()
> returns, 'a' goes out-of-scope. Fortran normally deallocates
> an unsaved allocatable entity, but 'a' is an unsaved local variable
> with the pointer attribute. For lack of a better term, 'allocate(a)'
> allocates an anonymous target and associates the anonymous target
> with the pointer 'a'. save_ptr() caches the address of the anonymous
> target. When init() returns does the anonymous target get deallocated
> or does the program leak memory?
Neither. If there were no C_PTR pointing to the memory, it would
leak memory.
> In addition, when init() returns,
> what happens to the pointer association of 'a'?
'a' becomes undefined, hence it is no longer associated with the
memory.
> I think it becomes
> undefined, which means the anonymous memory is inaccessible at least
> by Fortran means as there are no pointers associated with the
> anonymous target.
That is not correct. Looking at F2018, 18.2.3.3, by using C_F_POINTER,
you can
" Associate a data pointer with the target of a C pointer and specify
its shape. "
First, this talks about a C pointer having a target. Second, you can
re-estabilsh the association to a different pointer to the Fortran
program.
Regards
Thomas
More information about the Fortran
mailing list