# array problem.

• 08-21-2007
pessi
array problem.
Dear All

I have the following code which gives a segmentation fault. I dont think the array size is too large to result in a segmentation fault.

int xdim = 36;
int ydim = 256;
int zdim = 256;

double ***something = (double ***)malloc(xdim * sizeof(double **));
for(i=0; i< xdim; i++)
something[i] = (double **)malloc(ydim * sizeof(double *));

for(j=0; j< ydim; j++)
something[i][j] = (double *)malloc(zdim * sizeof(double));

for(i=0; i< xdim; i++)
for(j=0; j< ydim; j++)
for(k=0; k< zdim; k++)
something[i][j][k] = 1.0;

• 08-21-2007
MacGyver
Next time use code tags btw. They are there for a reason and display a healthy amount of respect for those you are asking to help you.

A double is usually 8 bytes I believe.... Let's see.....8 bytes * 36 * 256 * 256.......

/me pulls out his calculator.

Hmm..... 18,874,368 bytes. That is.... um..... 18,432 KB..... which is..... 18 MB.

Mmkay, so you're allocating 18 MB of data, but you're not checking if malloc() is failing or not. Why?
• 08-21-2007
pessi
My apologises for not adding the code tags.

I added the allocation check to make no difference. I still get the sedmentation fault and not the memory allocation failure message. The full code is here.

Code:

```int xdim = 36; int ydim = 256; int zdim = 256; double ***something = (double ***)malloc(xdim * sizeof(double **)); for(i=0; i< xdim; i++) something[i] = (double **)malloc(ydim * sizeof(double *)); for(j=0; j< ydim; j++) something[i][j] = (double *)malloc(zdim * sizeof(double)); if(something == NULL) { printf("Couldnt allocate memory"); exit(0); } for(i=0; i< xdim; i++) for(j=0; j< ydim; j++) for(k=0; k< zdim; k++) something[i][j][k] = 1.0;```
Cheers,
• 08-21-2007
pessi
solved.

Code:

```for(i=0; i< xdim; i++) something[i] = (double **)malloc(ydim * sizeof(double *)); for(j=0; j< ydim; j++) something[i][j] = (double *)malloc(zdim * sizeof(double));```
should be

Code:

```for(i=0; i< xdim; i++) something[i] = (double **)malloc(ydim * sizeof(double *)); for(i=0; i< xdim; i++) for(j=0; j< ydim; j++) something[i][j] = (double *)malloc(zdim * sizeof(double));```