为什么会出现分段错误?

orl*_*rlp 0 c struct segmentation-fault

我惊呆了,为什么这段代码会给我一个分段错误?

#include <stdio.h>

#define LIMIT 1500000

typedef struct {
    int p;
    int a;
    int b;
} triplet;

int main(int argc, char **argv) { 
    int i;
    triplet triplets[LIMIT];

    for (i = 0; i < LIMIT; i++) {
        triplets[i].p = 9; // remove this line and everything works fine
    }

    printf("%d\n", triplets[15].p);

    return 0; 
}
Run Code Online (Sandbox Code Playgroud)

编辑:将LIMIT更改为150后,我不再出现分段错误,而是打印随机数.

编辑2:现在我知道网站名称代表什么:)我使数组全局,现在一切正常.

Car*_*rum 10

堆栈溢出!以每个记录12个字节(假设为4个字节int)分配1500000条记录,需要超过17 MB的堆栈空间.使您的triplets数组全局或动态分配它.

至于你的编辑 - 缩小数组可能会阻止堆栈溢出,但你的printf()调用仍会打印未初始化的数据 - triplets[15].p可能是你打印出来时的任何内容.