Memory allocation issue with fortran and C program

Viewed 90

I have a fortran code that I am trying to get to work for my research purposes. The fortran code passes an integer variable and an integer size into a C program that will allocate memory. The code consists of a pointer "iarrays" that point to "arrays(1)". I get a segmentation fault with the following message: Segmentation Fault

The following is the fortran Code:

      subroutine initmem
c-----initial memory setup

      pointer ( iarrays , arrays(1) )
      
c-----allocate pointer memory for blocks and set blocks index pointers
      lpoint(0,1) = 0
c-----first call to lpoinst computes storage requirements
      call lpoinst
c-----Returns kplast = 1138280 which is the No. of bytes for pointered arrays. I have verified lpoinst works correctly
      nwdinc = kplast - lpoint(0,1)

Array lpoint after lpoinst function

c-----nbytaddr = 1
      call getmem (lpoint(0,1), (nwdinc*nbytaddr))
c-----Note:getmem is a fortran file only used to check if memory is allocated. I have not included the code in this post.  

c-----getmem.F calls C program memalloc(lpoint(0,1), (nwdinc*nbytaddr)) 
c-----memalloc.c code attached below
c-----value of lpoint(0,1) = -1431465968

c-----second call to lpoinst sets pointers with updated lpoint(0,1).
      call lpoinst

Array lpoint after lpoint(0,1) was updated

      iarrays = lpoint(0,1)
      isize = nwdinc / addrinc
      do 100 i=1,isize
        arrays(i) = zero
 100  continue

      return
      end

Here is the C program memalloc.c:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>

#ifdef _CRAY
int MEMALLOC (nextptr, size)
#else
#ifdef POST_UNDERSCORE
int memalloc_ (nextptr, size)
#else
int memalloc (nextptr, size)
#endif
#endif

int *size;
int *nextptr;
{
  void *ptr;
  printf("Size Address:%d Size Value: %d \n", size, *size);
  printf("nextptr Address:%d nextptr Value: %d \n", nextptr, *nextptr);
  printf("ptr before hexa: %p ptr before int: %d \n", (void *) ptr, (int *) ptr );
  if (*nextptr == NULL) {
    if ((ptr = (void *) malloc (*size)) == NULL) {
      return(-1);
    }
  }
  else {
    if ((ptr = (void *) realloc (*nextptr, *size)) == NULL) {
      return(-1);
    }
  }
  printf("ptr after hexa: %p ptr after int: %d \n", (void *) ptr, (int *) ptr );
  *nextptr = (int) ptr;
  printf("nextptr Address:%d nextptr Value: %d \n", nextptr, *nextptr);
  return (0);
}

Print statements in memalloc.c

The pointer iarrays is set to a negative value. Can the value of that pointer be negative? Why is not able to access the memory for arrays(i)? Can someone help me get through this segmentation fault?

Thank you!

0 Answers
Related