Deallocation of arrays passed as c_ptr

A Fortran pointer is very different object from a C pointer. Basically a C pointer is just a base address, while a Fortran pointer is a complex (and hidden) descriptor. In your dealloc_pointer() routine you are reconstructing a Fortran pointer from a C pointer: it is supposed to have the same characteristics, but this is formally not the same object as the initial pointer that was allocated.

I think that such code might work, but it’s probably not standard compliant. The F2023 standard says in in the 9.7.3.3 section:

Deallocating a pointer that is disassociated or whose target was not created by an ALLOCATE statement causes an error condition in the DEALLOCATE statement

In your code the target is hidden in the c_f_pointer() function, and the runtime cannot determine how it had been initially allocated. This minimal example runs apparently fine with gfortran but crashes with the Intel compiler:

program foo
use iso_c_binding
implicit none

integer, pointer :: p(:), q(:)

allocate( p(1000) )
call c_f_pointer(c_loc(p),q,[1000])
deallocate(q)

end
3 Likes