#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
long int length = atol(*++argv);
long int a[length];
// write and read it, so it doesn't get optimized out:
for (int i = 0; i < length; ++i)
a[i] = i;
for (int i = 0; i < length; ++i)
if (a[i] != i)
return 1;
}
The program above runs in most cases, however when I try to initialise the array a
with a large number (such as 1967791
) I get a segmentation fault. Is there a way I can allocate more memory to the program so this doesn't happen?
I am running this program on a Virtual Machine using Linux.
You need to allocate memory on the heap, rather than on the stack:
long int *a = malloc(array_length * sizeof *a);
Don't forget to free()
it when it's no longer needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.