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 <std开发者_Go百科io.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.
That might be bigger than your stack. You can
- Make
large
global - Use
malloc
The array is too big to fit on your stack. Use the heap with char *large = malloc(S)
instead.
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 write char* 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.
Large is being allocated on the stack and you are overflowing it.
Try using char *large = malloc(S)
精彩评论