memory problem on 3D array - segmentation fault

I want to make a big 3D array called u3d,

so I declared it with the following sentence:
nx=4096;
ny=400;
nz=129;
double u3d[nx][ny][nz];


C++ repeatedly gives the following error message:
/bin/sh: line 1: 4587 Segmentation fault

If I set nx up to 30, it's OK, but if nx is greater than 30,
segmentation fault messages occur.

Am I using a too big array to handle in my system?
I cannot understand since in Fortran there was no problem with the following
command:
real, allocatable, dimension(:,:,:) :: u3d
allocate(u3d(1:nx,1:ny,1:nz))


closed account (S6k9GNh0)
Allocate it on heap via the new operator. The array is too large for the stack:

double *u3d = new double[nx][ny][nz]

Also, using variables to specify the size of stack arrays should be illegal. NOTE: Though GCC allows it, it still warns you as it isn't a flexible method of allocation and will not compile on any others. GCC is breaking the specification at the users expense which most do not.
Last edited on
Dynamically allocate the array. Depending upon the OS you'll have compile time allocation size issues.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
double *** u3d;

u3d = new double ** [nx];
if (NULL = u3d)
   //Handle error;
else
{
  for (int i = 0; i < nx; i++)
  {
     u3d[i] = new double *[ny];
     if (NULL == u3d[i])
     {
         //Handle Error
         //and unwind the allocations
     }
     else
     {
        for (int j = 0; j < ny; j++)
        {
           u3d[i][j] = new double [nz];
           if (NULL = u3d[i][j])
           {
               //Handle Error
               //and unwind the allocations
           }
        }
     }
  }
}


You'll also need to deallocate when finished using

1
2
3
4
5
6
7
8
9
for (int i = 0; i < nx; i++)
{
   for (int j = 0; j < ny; j++)
   {
       delete [] u3d[i][j];
   }
   delete [] u3d[i]
}
delete [] u3d;


Or something similar. Didn't compile this.
Topic archived. No new replies allowed.