简体   繁体   English

C程式码:EXC_BAD_ACCESS

[英]C programming: EXC_BAD_ACCESS

I am writing in C this simple program, using xcode. 我正在用Xcode用C编写这个简单的程序。

#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); 我将以下消息附加到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. Xcode应该不会有问题,因为在Eclipse中无论如何都不会进行任何打印。

I'm not quite sure why you observe EXC_BAD_ACCESS . 我不太确定为什么您要观察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. 首先,将B传递给printf并要求其将其格式化为整数。 It is not an integer. 它不是整数。 You should use %p if you want to treat it as a pointer. 如果要将%p视为指针,则应使用%p

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. 最大的是A ,它的sizeof(double)*200*200*2*1*2*2 ,即256万字节。 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. Mac OS X上的默认堆栈大小为8 MiB(8192 KiB)-在终端中尝试ulimit -sulimit -a

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)). 您有大约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; 您还有3个其他的double数组,它们的大小是原来的一半; you have 2 arrays of int that are 1/4 the size. 您有2个大小为1/4的int数组。 These add up to 7.560 MB (7.4 MiB). 这些总计达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. 甚至G,H和I也使用了适量的堆栈空间:总的来说,它们和D一样大,因此它们使用大约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. 您可以使它们成为文件作用域数组,也可以使用malloc()等动态分配它们。

Why on earth would you have a dimension of [1] ? 为什么在地球上会有[1]的维? You can only ever write 0 as a valid subscript, but then why bother? 您只能将0写为有效下标,但是为什么要麻烦呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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