program test2
  use iso_c_binding

  type(c_ptr) :: cp
  integer :: n
  character(len=1), pointer :: cc(:)

  interface
    subroutine getdata(cp, n) bind(c, name="getdata")
      use iso_c_binding
      type(c_ptr) :: cp
      integer :: n
    end subroutine getdata
  end interface

  !! interface to call C free from fortran
  interface
    subroutine c_free(a) bind(c, name='free')
      !! interface to call c free to free memory
      use iso_c_binding
      type(c_ptr), value :: a
    end subroutine c_free
  end interface
  
  cp = c_null_ptr
  n = 5
  call getdata(cp, n)
  !! use cp .....

  !! how to free the memory?
  !!call c_free(cp) ! failed
  !!print *, 'c_free(cp) done'

  call c_f_pointer(cp, cc, shape=(/n/))
  deallocate(cc)  ! also failed
  print *, 'deallocate cc done'
  
end program test2

subroutine getdata(cp, n) bind(c, name="getdata")
  use iso_c_binding
  type(c_ptr) :: cp
  integer :: n
    
  character(len=1), pointer :: cc(:)

  allocate (cc(n))
  print *, 'allocated cc'
  cp = c_loc(cc)
  
end subroutine getdata
