0

Im trying to allocate memory for a 3-dimentional character array of [10][10][2]. When setting all of the values to space there is a segmentation fault: 11 at [0][2][1]. Here is the code:

aiBoard =(char ***) calloc(SIZE,sizeof(char **));

for(i = 0; i < SIZE;i++)
{
    aiBoard[i] = (char **)calloc(SIZE, sizeof(char*));
}
for(i = 0;i < SIZE;i++)
{
    for(j = 0; j < 2; j++)
    {
        aiBoard[i][j] = (char*)calloc(2,sizeof(char));
    }

}

for(i = 0; i < SIZE; i++)
{
    for(j = 0; j < SIZE; j++)
    {
        for(k = 0; k < 2; k++)
        {
            aiBoard[i][j][k] = ' ';
        }
    }
}
Andrew B.
  • 167
  • 2
  • 10
  • 2
    You mix `SIZE` and `2` for second level. (`j`) – user13500 Dec 08 '14 at 02:33
  • You actually allocate dimensions `[10][2][2]` - change the first `j < 2` to `j < 10`. It would be clearer to have a single set of nested loops instead of 3 of them. – M.M Dec 08 '14 at 02:39
  • I see what you mean but it's allocating to much memory. – Andrew B. Dec 08 '14 at 02:40
  • Note that if you do not need to resize the final two dimensions once you have created the array, then you can allocate it [with a single malloc call](http://stackoverflow.com/a/13672436/1505939) – M.M Dec 08 '14 at 02:48

1 Answers1

0

What value of SIZE did you use? 0 or 1 would cause a crash, and more than 2 would make it crash. Are you using SIZE everywhere you really to? Otherwise you are only calloc - ing 2 and other uses of the hard coded '2'...should be changed to SIZE

like this:

for(i = 0;i < SIZE;i++)
{
    for(j = 0; j < SIZE; j++)
    {
        aiBoard[i][j] = (char*)calloc(SIZE,sizeof(char));
    }

}

for(i = 0; i < SIZE; i++)
{
    for(j = 0; j < SIZE; j++)
    {
        for(k = 0; k < SIZE; k++)
        {
            aiBoard[i][j][k] = ' ';
        }
    }
}

Really you should have three sizes

#define iSIZE (10)
#define jSIZE (10)
#define kSIZE (2)

and

  for(i = 0;i < iSIZE;i++)
    {
        for(j = 0; j < jSIZE; j++)
        {
            aiBoard[i][j] = (char*)calloc(jSIZE,sizeof(char));
        }

    }

for(i = 0; i < iSIZE; i++)
{
    for(j = 0; j < jSIZE; j++)
    {
        for(k = 0; k < kSIZE; k++)
        {
            aiBoard[i][j][k] = ' ';
        }
    }
}
Grantly
  • 2,546
  • 2
  • 21
  • 31