So I am now rewriting my fortran code in C, and apparently I do not understand how to properly use malloc and pointers. I am trying to make the main function just nice and neat calls to other functions, which need to malloc arrays. So, I am passing pointers of pointers to them.
But the right amount of memory is not being allocated so I get segmentation faults.
The commented out function headers are where I just tried to make everything a global variable, so I didn;t have to worry about all the pointers. But that just gives the exact same error.
D above has a value of 125, so for example *etemp needs to be an array of size 125, but sizeof(*etemp)/sizeof(*etemp[0]) prints 2.
But the right amount of memory is not being allocated so I get segmentation faults.
Code:
#include <stdio.h>
#include <stdlib.h>
//#include <cuda.h>
#include <math.h>
//#include "cublas.h"
typedef float real;
typedef struct{
real * amp;
} t_ampl;
typedef struct{
int * ket;
} blk;
typedef struct{
int nx;
int ny;
int nz;
int sz;
int tz;
} states;
void set_SPB(real **,int,states **,states **,int **);
//void set_SPB();
const real hc =197.32697,pi=3.1415927;
int main(){
int nmax = 2, A = 28;
real *etemp, *fock;
int *Ndex,*lookup,*lookup_a;
states *channel,*SPB;
//!generates the single particle basis to be used
set_SPB(&etemp,nmax,&SPB,&channel,&Ndex);
//set_SPB();
// set_chan(); // !organizes the SPB into proper channels
// set_ph_chan(); //! ph-formalism
// ini_diagrams(); //!calculates mbpt2 energy and interactions
//CCD_iter; !iteratively solves the CCD equations
free(etemp);
free(Ndex);
free(SPB);
return 0;
}
void set_SPB(real **etemp,int nmax,states **SPB,states **channel,int **Ndex){
//void set_SPB(){
int tot_orbs = (2*nmax+1)*(2*nmax+1)*(2*nmax+1)*4;
int D = tot_orbs/4;
int Nalpha = (2*nmax+1)*(2*nmax+1)*(2*nmax+1)*9;
real E;
*etemp = (real *) malloc(D*sizeof(float));
*Ndex = (int *) malloc(D*3);
*SPB = (states *) malloc(tot_orbs);
printf("orbits without spin degeneracy %d \n",D);
printf("size of etemp %ld \n",sizeof(*etemp)/sizeof(*etemp[0]));
return;
int i = 0;
for(int nx =-nmax;nx<=nmax;nx++){
for(int ny =-nmax;ny<=nmax;ny++){
for(int nz =-nmax;nz<=nmax;nz++){
E = 0.5*4.0*pi*pi*(nx*nx+ny*ny+nz*nz);
//printf("%d\n",i);
etemp[i] = &E;
Ndex[0*D+i] =&nx;
Ndex[1*D+i] = &ny;
Ndex[2*D+i] = &nz;
i+=1;
}
}
}
printf("Seg Fault\n");
return;
}
The commented out function headers are where I just tried to make everything a global variable, so I didn;t have to worry about all the pointers. But that just gives the exact same error.
D above has a value of 125, so for example *etemp needs to be an array of size 125, but sizeof(*etemp)/sizeof(*etemp[0]) prints 2.