-
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;
Thanks in advance,
Prasad.
-
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?
-
added allocation failure
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;
Thank you for your reply.
Cheers,
prasad.
-
solved.
Thank you for your reply...I solved the problem.
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));
Thank you for your help.
Cheers,
Prasad..
-
Congrats on solving it, but just as an fyi, your allocation check you did was kind of late. If malloc() failed, you would still be getting a seg fault becase you'd be derefencing and using a NULL pointer. ;)
-
Check the FAQ on casting malloc in C
-
thank you both for your assistance.