Reputation: 13
I am working on a project that deals with a struct and has various functions that manipulate the given struct.
I have started off with my initial function that just allocates the memory for the struct, and initialises each item in the struct and then returns a pointer to the struct. I have already defined the struct in my header file. I then have a main file that I will eventually use to run all my functions, however I am having trouble just running this first one, it seg faults every time I run it.
header:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <limits.h>
struct Double_Array{
double** array;
int rowsize;
int colsize;
};
struct Double_Array* double_array(int,int);
function:
#include "header.h"
struct Double_Array* double_array( int row, int col){
int i;
struct Double_Array* ptrDouble_Array;
ptrDouble_Array = (struct Double_Array*) malloc(sizeof(struct Double_Array));
ptrDouble_Array -> rowsize = row;
ptrDouble_Array -> colsize = col;
for(i=0;i< ptrDouble_Array -> colsize ; i++){
ptrDouble_Array -> array[i] = malloc((sizeof(double))*(row));
}
return(ptrDouble_Array);
}
mainline:
#include "header.h"
int main(){
srand(time(0));
printf("running");
int i;
int j;
struct Double_Array* ptr;
ptr = double_array( 5, 5);
for(i=0;i<5;i++){
free(ptr->array[i]);
}
free(ptr);
return(0);
}
I've spent a while looking for possible issues, but everything looks logically correct to me.
What is causing the Seg fault
Upvotes: 1
Views: 150
Reputation: 225767
You're allocating space for each array[i]
, but you never allocate space for array
. So ptrDouble_Array->array[i]
is dereferencing an uninitialized pointer, which causes the segfault.
Add the allocation:
ptrDouble_Array->array = malloc((sizeof(double *))*(col));
for(i=0;i< ptrDouble_Array->colsize ; i++){
ptrDouble_Array->array[i] = malloc((sizeof(double))*(row));
}
And don't forget to free
it:
for(i=0;i<5;i++){
free(ptr->array[i]);
}
free(ptr->array);
free(ptr);
Upvotes: 3