简体   繁体   中英

C programming: EXC_BAD_ACCESS

I am writing in C this simple program, using xcode.

#include <stdio.h>
int main()
{
    double A[200][200][2][1][2][2];
    int  B[200][200][2][1][2];
    int  C[200][200][2][1][2];
    double D[200][200][2][1][2];
    double E[200][200][2][1][2];
    double F[200][200][2][1][2];

    double G[200][200];
    double H[200][200][2];
    double I[200][200];
    double L[50];



    printf("%d",B);

    return 0;
}

I get the following message attached to printf("%d",B);

Thread 1: EXC_BAD_ACCESS (code=2, address= ….)

So basically is telling me that I messed up with the memory. How can that be possible?

BUT, if I comment

// int  C[200][200][2][1][2];

it works perfectly.

Any clue? It should not be a problem with Xcode since in Eclipse does not printf anything in any case.

I'm not quite sure why you observe EXC_BAD_ACCESS . But your code is quite broken. For a start, you pass B to printf and ask it to format it as an integer. It is not an integer. You should use %p if you want to treat it as a pointer.

The other problem is that your local variables will be allocated on the stack. And they are so big that they will overflow the stack. The biggest is A which is sizeof(double)*200*200*2*1*2*2 which is 2,560,000 bytes. You cannot expect to allocate such large arrays on the stack. You'll need to switch to using dynamically allocated arrays.

The default stack size on Mac OS X is 8 MiB (8,192 KiB) — try ulimit -s or ulimit -a in a terminal.

You have an array of doubles running at about 2.5 MiB (200 x 200 x 2 x 1 x 2 x 2 x sizeof(double)). You have 3 other arrays of double that are half that size; you have 2 arrays of int that are 1/4 the size. These add up to 7.560 MB (7.4 MiB). Even G, H and I are using a moderate amount of stack space: in aggregate, they're as big as D, so they use about 1 MiB.

The sum of these sizes is too big for the stack. You can make them file scope arrays, or you can dynamically allocate them with malloc() et al.

Why on earth would you have a dimension of [1] ? You can only ever write 0 as a valid subscript, but then why bother?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM