0

I'm currently experiencing an memory issue: I have a main program coded in Fortran which calls a C/C++ subroutine to perform some tasks and store data in a dynamically allocated array. The thing is I need to have access to these data when back to the Fortran main program. I tried to declare a C pointer (TYPE(C_PTR)) in fortran to point to the array but it doesn't seem to work. The array is present within the C subroutine but I get a segfault when trying to access it when I'm back to the main Fortran program. I give my code here, any ideas? Thank you for helping !!

Fortran:

PROGRAM FORT_C
use iso_c_binding
IMPLICIT NONE

    interface
        subroutine call_fc(pX,s) bind(C,name='call_fc_')
            import
            integer(c_int)              :: s
            type(c_ptr), pointer        :: pX
        end subroutine
    end interface

    integer(c_int)                              :: i
    integer(c_int)                              :: s
    integer(c_int), pointer                     :: X(:)
    type(C_ptr), pointer                        :: pX

    s=100

    call call_fc(pX,s)
    call c_f_pointer(pX,X,(/s/))

    ! This here provocates a segfault
    do i=1,s
        write(*,*), i
        write(*,*) X(i)
    end do

END

C subroutine:

#include <iostream>
#include <cstdlib>

using namespace std;

extern "C" 
{
    void call_fc_(int **x, int *s);
    void c_func_deallocate(int **x);
}


void call_fc_(int **x, int *s)
{
    int *y = (int *) malloc(sizeof(int)*(*s));
    for(int i=0; i < *s+10; i++)
    {
        cout << i << endl;
        y[i]=i;
    }
    *x = y;
}

void c_func_deallocate(int **x)
{
    free(*x);
}

Outpout:

           1
forrtl: severe (174): SIGSEGV, segmentation fault occurred
Image              PC                Routine            Line        Source             
exemple            0000000000402E1F  Unknown               Unknown  Unknown
exemple            0000000000402C8C  Unknown               Unknown  Unknown
libc.so.6          000000331241ECDD  Unknown               Unknown  Unknown
exemple            0000000000402B89  Unknown               Unknown  Unknown
M. S. B.
  • 28,968
  • 2
  • 46
  • 73
Pleurk
  • 58
  • 4
  • 3
    You've allocated an array `y` of size `s` integers, and then are writing up to element `s+10`. You also don't want `pX` in the inter face to have the `pointer` attribute - being of type `c_ptr` is what is needed here. – Jonathan Dursi May 07 '14 at 13:52
  • Yes sorry the "*s+10" was just for a test (checking the bounds), I removed it after. But in fact the problem was the "pointer" attribute of pX, I removed it and now it works fine, thanks a lot Jonathan ! – Pleurk May 07 '14 at 13:54
  • If you use `bind(c)` you don't have to worry about function name mangling. You can name the C function `call_fc` and the Fortran interface `call_fc`. – bdforbes May 08 '14 at 22:36

0 Answers0