Fortran ISO_C_BINDING C_F_POINTER C memory ownership at the C-Fortran boundary
0 reputation · 01 Feb 2021, 16:10 UTC
Goal: expose a C-allocated object to Fortran using C_F_POINTER and determine which language owns the memory and when the Fortran pointer becomes invalid.
ISO_C_BINDING states that C_F_POINTER does not transfer ownership or finalization, and access after the C object is freed is undefined behavior. Derived types with allocatable or pointer components are not interoperable with C, so layout and lifetime depend on the compiler, ABI, and standard mode. The deallocation boundary is therefore not fixed by the language standard alone.
What deallocation sequence keeps the Fortran pointer valid until the final access? Is it safe for Fortran to request C free through a BIND(C) procedure, or must C retain lifetime control? Must the C allocator outlive every Fortran reference in standard-conforming code?