Possible bad memory management in Fortran-C interfacing

@mEm ,

It’s unclear what exactly you’re doing. Ostensibly it would appear you are dealing on the Fortran side with a subprogram interface along the following lines:

module m
   use, intrinsic :: iso_c_binding, only : c_int
contains
   subroutine sub( n ) bind(C, name="sub")
      integer(c_int), allocatable, intent(inout) :: n
      n = 42
   end subroutine 
end module 

Toward which you are trying do the following on the C side with the hope of eschewing verbosity:

#include <stdlib.h>
void sub( int * );
int main() {
    int *x;
    x = (int *)malloc( sizeof(int *) );
    *x = 0;
    sub(x);
    free(x);
}

But try it, you will see that it won’t work, the Fortran subprogram in such a case is not interoperable with such an approach due to the ALLOCATABLE attribute of argument n.

It is with this in mind as you’d shown in your original post that I pointed to you the enhanced interoperability facilities from Fortran 2018 that allow the Fortran subprogram - as shown - to be consumed via a C companion processor. Sure, it leads to a bit of additional verbosity on the C side but the advantage is all in Fortran - the code there remains compact and efficient and one can interoperate arguments which are of assumed-shape and/or have the ALLOCATABLE attribute and so forth.

// option that works
#include <stdio.h>
#include "ISO_Fortran_binding.h"
void sub( CFI_cdesc_t * );
int main() {
    CFI_CDESC_T(0) cx;
    int irc;
    irc = CFI_establish((CFI_cdesc_t *)&cx, NULL,
      CFI_attribute_allocatable,
      CFI_type_int, sizeof(int), 0, NULL);
    sub((CFI_cdesc_t *)&cx);
    printf("C main - x: %d", *(int *)cx.base_addr);
    irc = CFI_deallocate((CFI_cdesc_t *)&cx);
}
C:\temp>ifort /c /free /standard-semantics m.f
Intel(R) Fortran Intel(R) 64 Compiler Classic for applications running on Intel(R) 64, Version 2021.9.0 Build 20230302_000000
Copyright (C) 1985-2023 Intel Corporation.  All rights reserved.


C:\temp>cl /c /W3 /EHsc c.c
Microsoft (R) C/C++ Optimizing Compiler Version 19.34.31937 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

c.c

C:\temp>link c.obj m.obj /subsystem:console /out:c.exe
Microsoft (R) Incremental Linker Version 14.34.31937.0
Copyright (C) Microsoft Corporation.  All rights reserved.


C:\temp>c.exe
C main - x: 42