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.
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.