Deep Arora
Deep Arora

Reputation: 2040

EXC BAD ACCESS when writing C code in iOS app

I am trying to achieve some functionality using pure c programming language in ios app. The code runs fine when the square matrix size is 50(w=h=50). If I increase the size of matrix to 100, I get EXC BAD ACCESS message. Below is the code I am using:

    double solutionMatrixRed[w][h];
    double solutionMatrixGreen[w][h];
    double solutionMatrixBlue[w][h];
    double solutionMatrixAlpha[w][h];

    for(int x=0;x<w;x++)
    {
        for(int y=0;y<h;y++)
        {

            //NSLog(@"x=%d y=%d",x,y);
            solutionMatrixRed[x][y] = 0;
            solutionMatrixGreen[x][y] = 0;
            solutionMatrixBlue[x][y] = 0;
            solutionMatrixAlpha[x][y] = 0;
        }
    }

Even if w=h=100, the total size should be 100*100*8 Bytes which 80KB, which is normal. Can anyone tell what could be wrong ?

Upvotes: 2

Views: 225

Answers (3)

Rami Jarrar
Rami Jarrar

Reputation: 4643

Because you're trying to allocate all that memory on the stack. while you should allocate it on the heap, using dynamic allocation (malloc):

double **solutionMatrixRed = malloc(h * sizeof(double *));
for(i=0; i<h; i++)
    solutionMatrixRed[i] = malloc(w * sizeof(double));

Upvotes: 1

Man Vs Code
Man Vs Code

Reputation: 1057

I believe the stack size in iOS is limited to 512 KB. At w = 100 and h = 100, your arrays would require about 312.5 KB. I suspect that you are exceeding the stack size and should attempt at allocating the arrays on the heap (use malloc() to allocate the arrays).

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726939

Your code allocates all four matrices in the automatic storage*, which may be limited. Even four times 80K may be too much for a mobile device.

If you need to deal with that much memory, consider allocating it from the dynamic memory using malloc:

double (*solutionMatrixRed)[h] = malloc((sizeof *solutionMatrixRed) * w);
// allocate other matrices in the same way, then do your processing
free(solutionMatrixRed); // Do not forget to free the memory.


* Often referred to as "stack", by the name of the data structure that is frequently used in the implementation of automatic storage.

Upvotes: 3

Related Questions