大小为 2^25 的数组
我试图在 c 中创建一个大小为 2^25 的数组,然后对其执行一些基本操作(memsweep 函数)。 c代码,但在执行时会出现分段错误。
#include <stdio.h>
#include <time.h>
#define S (8191*4096)
main()
{
clock_t start = clock();
unsigned i;
volatile char large[S];
for (i = 0; i < 10*S; i++)
large[(4096*i+i)%S]=1+large[i%S];
printf("%f\n",((double)clock()-start)/CLOCKS_PER_SEC);
}
我可以编译
I am trying to create an array of size 2^25 in c and then perform some elementary operations on it (memsweep function). The c code is
#include <stdio.h>
#include <time.h>
#define S (8191*4096)
main()
{
clock_t start = clock();
unsigned i;
volatile char large[S];
for (i = 0; i < 10*S; i++)
large[(4096*i+i)%S]=1+large[i%S];
printf("%f\n",((double)clock()-start)/CLOCKS_PER_SEC);
}
I am able to compile it but on execution it gives segmentation fault.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这可能比你的堆栈还要大。您可以
large
全局malloc
That might be bigger than your stack. You can
large
globalmalloc
该数组太大,无法放入您的堆栈中。请改用
char *large = malloc(S)
堆。The array is too big to fit on your stack. Use the heap with
char *large = malloc(S)
instead.你没有那么多的堆栈空间来分配这么大的数组......例如,在 Linux 上,堆栈大小通常为 8192 字节。你肯定已经超出了这个范围。
最好的选择是使用
malloc()
在堆上分配内存。因此,您可以编写char* large = malloc(S);
。您仍然可以使用[]
表示法访问该数组。或者,如果您使用的是 Linux,您可以在命令行上调用 sudo ulimit -s X ,其中 X 是一个足够大的数字,足以让您的数组适合堆栈......但我会通常不鼓励这种解决方案。
You don't have that much stack space to allocate an array that big ... on Linux for instance, the stack-size is typically 8192 bytes. You've definitely exceeded that.
The best option would be to allocate the memory on the heap using
malloc()
. So you would writechar* large = malloc(S);
. You can still access the array using the[]
notation.Optionally, if you're on Linux, you could on the commandline call
sudo ulimit -s X
, where X is some number large enough for your array to fit on the stack ... but I'd generally discourage that solution.正在堆栈上分配大容量,并且您正在溢出它。
尝试使用 char *large = malloc(S)
Large is being allocated on the stack and you are overflowing it.
Try using
char *large = malloc(S)