0

Hi I have a triple pointer that I want to realloc when my original array is filled up. For some reason, the way I'm using realloc gives me a seg fault. Anybody have a sense why?

double ***matrixn;
matrixn=(double***) calloc(1,sizeof(double **));
for(i=0;i<1;i++){
    matrixn[i]=(double**)calloc(3,sizeof(double*));
    for(j=0;j<3;j++){
        matrixn[i][j]=(double*)calloc(4,sizeof(double));
    }
}

max_size=1

This next part takes place inside of a loop:

max_size+=1;

matrixn=realloc(matrixn,max_size*sizeof(double**));
matrixn[max_size-1]=(double**)calloc(3,sizeof(double*));

for (i=0;i<3;i++){
matrixn[max_size-1]=(double*)calloc(4,sizeof(double));
}

Thanks

JupiterOrange
  • 339
  • 2
  • 6
  • 18
  • 2
    General note: If using a C compiler (as opposed to a C++ compiler), do not cast the result of the `alloc` family of functions. – paddy Jan 23 '13 at 20:40
  • 1
    It's a language stipulation in C that you don't cast the result. It's a `void*`, and can be directly assigned to another type without a cast. – paddy Jan 23 '13 at 20:43
  • What happens if realloc fails? You've lost your old matrixn, which isn't being free()'d and will thus leak, and the next line of code crashes because your new matrixn is NULL. I suggest storing the return value of realloc into a temp variable, and deciding what to do from there. – autistic Jan 23 '13 at 21:53

1 Answers1

2

In the loop of your second code block, you forgot index i. It should instead look like

matrixn[max_size-1][i]=(double*)calloc(4,sizeof(double));
s.bandara
  • 5,636
  • 1
  • 21
  • 36