SIGSEGV, memory allocation/freeing problem
Hello, I'm getting the following message in gdb:
Program received signal SIGSEGV, Segmentation fault.
0x400cc1ce in _IO_flush_all () at genops.c:825
825 genops.c: No such file or directory.
in genops.c
when running the code given below.
File main.c:
Code:
1: int main(){
2: extern int *p; //defined in main.h (not shown here)
3: extern int **a; //dito line 2
4:
5: p=ivector(1,K); //defined in nrutil.c from "Numerical Recipes in C" W.H.Press et al.
6: p=read_p(); //prototype in main.h
7: a=imatrix(1,K,1,N); //dito to comment on line 5
8: a=read_a(); //prototype in main.h
9:
10: //printing p and a here works fine.
11:
12: free_ivector(p,1,K); //dito to comment on line 5
13: free_imatrix(a,1,K,1,N); //dito to comment on line 5
14: return 0;
15: }
the functions are given in another read_file.c (and probably not relevant to the problem?).
File read.c:
Code:
int *read_p(void){
char line[4];
FILE *file;
int i=1;
extern int *p;
file = fopen("data_p.dat","r");
while(fgets(line,sizeof(line),file)!=NULL)
sscanf(line,"%i", &p[i++]);
free(file);
return p;
}
int **read_a(void){
char line[4];
FILE *file;
int i=1, j=1;
extern int **a;
file = fopen("data_a.dat","r");
while(fgets(line,sizeof(line),file)!=NULL){
sscanf(line,"%i", &a[i][j]);
//appropriate incrementing of i and j guaranteed
}
free(file);
return a;
}
When I comment out either lines 2, 5, 6 and 12 (vector p) or lines 3, 7, 8, and 13 (matrix a) in main.c, it works fine.
But together, it seems there is some sort of endless loop running after line 14, that is, the code runs fine up to the return command.
Thanks for your time looking into this and your comment!
Michael