Undefined association status after c_f_pointer(c_null_ptr) in iso_c_binding
0 reputation · 13 Oct 2025, 00:17 UTC
0 reputation · 13 Oct 2025, 00:17 UTC
The goal is to convert a C pointer received through iso_c_binding into a Fortran pointer with c_f_pointer, then test association before dereferencing. The code must compile under Fortran 2003 through Fortran 2018 and remain repeatable when the compiler is changed.
The standard does not require a diagnostic when c_f_pointer receives c_null_ptr or an address that does not designate a valid Fortran object, and it leaves the resulting association status undefined. Compiler behavior varies: some abort, some produce a pointer that fails only on later use, and some appear to succeed. The difference is compiler-dependent rather than version-dependent within Fortran 2003-2018.
Is associated(fort_ptr) safe to call immediately after an invalid c_f_pointer conversion? Can a compiler flag or binding attribute make the failure deterministic? Should null C pointers be rejected before c_f_pointer is called, and is that precondition portable across compilers?
No, associated(fort_ptr) is not safe to call immediately after an invalid c_f_pointer(c_null_ptr) conversion. The Fortran 2003–2018 standard leaves the association status undefined in this case.
The standard requires no diagnostic; compiler behavior varies: some return .false., some appear to succeed, and some only fail on later dereferencing. The difference is compiler‑dependent, not version‑dependent.
c_f_pointer; this is not a language guarantee.associated() immediately after c_f_pointer to observe each implementation’s result.Which Fortran compiler and version are you targeting? This determines whether vendor‑specific diagnostics or workarounds are available and whether upstream validation is advisable.
Use comments to ask for clarification. Post a solution as an answer.
37,275 reputation · 13 Oct 2025, 03:30 UTC
The only portable guard is to test the C pointer before calling c_f_pointer. Since Fortran 2003, c_associated(c_ptr) (or c_ptr /= c_null_ptr) is well-defined and works across gfortran, ifort/ifx, nvfortran, and flang. Only when that test passes should you invoke c_f_pointer.
Even a non-null C pointer yields undefined association status if the referenced object’s type, kind, or rank differs from the Fortran pointer’s declaration. This is a separate UB source from null pointers and is not caught by c_associated.
function c_to_fptr(cptr) result(fptr)
type(c_ptr), intent(in) :: cptr
real(c_double), pointer :: fptr(:)
if (.not. c_associated(cptr)) then
nullify(fptr); return
end if
call c_f_pointer(cptr, fptr, [expected_size])
end function
Compile with -fcheck=pointer (gfortran) or -check pointers (ifx) to catch later dereference errors, but remember these flags do not make the initial association status defined.