解释为什么分配大数组会导致C中的分段错误 [英] Explanation of why allocating a large array results in segmentation fault in C
问题描述
我不太了解C,但是最近我一直在用这种语言编写一些程序来加快它的速度(它最初是用python编写的).因为我已经设法解决了原来的问题,所以我真的再也没有问题了.但是,我想知道为什么该解决方案有效.
I'm not too experienced in C, but I've been recently writing some program in the language to speed it up a little bit (it was originally written in python). I don't really have a problem anymore since I already managed to solve my original problem. However, I would like to know why this solution works.
我有一个数据结构,表示定义为的复数
I have a data structure representing complex numbers defined as
typedef struct _fcomplex { float re, im; } fcomplex;
然后我要创建一个复数数组,如下所示:
Then I want to create an array of complex numbers as:
fcomplex M[N];
这里N是一个很大的数字(约为10 ^ 6).然后,我在一个函数中将其初始化为零,该函数实际上会遍历所有索引并设置数组中的值.就像这样:
Here N is a large number (something like ~10^6). Then I initialize the array with zeros in a function that essentially runs through all the indices and sets the values in the array. It's something like:
fcomplex num = {0.0, 0.0};
int i;
for (i=0 ; i < N ; i++) {
M[i] = num;
}
但是,当我运行代码时,会导致分段错误.但是,如果我使用malloc()为数组分配空间,则为
However, when I run the code, it results in a segmentation fault. However, if I use malloc() to allocate space for the array instead as
fcomplex* M = malloc(N*sizeof(fcomplex));
然后像以前一样做所有事情,代码可以正常工作.另外,对于较小的N值,代码无论哪种方式都可以正常运行.
and then do everything as before, the code works fine. Also, for smaller values of N, the code runs fine either way.
正如我所说,使用malloc()已经解决了问题,但是我想知道为什么吗?
As I said, using malloc() already solved the problem, but I would like to know why?
推荐答案
这取决于您在何处分配了数组.如果它在函数内部,则该变量将分配在堆栈上,默认情况下(我假设您正在运行linux),堆栈大小为8Mb.
It depends where you allocated the array. If it's inside a function, then the variable is allocated on the stack, and by default, (I assume you're running linux) the stack size is 8Mb.
您可以使用ulimit -s
找到它,也可以修改此值,例如ulimit -s 1000000
.
You can find it out using ulimit -s
and also modify this value, for instance ulimit -s 1000000
.
您可能想看看这些问题:
You may want to have a look on those questions:
- 全局和局部变量的内存分配
- 大型阵列上的分段错误(由@Ed建议)
- Memory allocation for global and local variables
- Segmentation fault on large array sizes (suggested by @Ed)
这篇关于解释为什么分配大数组会导致C中的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!