Reputation: 35702
I want to create an array at runtime in C of approximately 10M rows, whose precise size is only known at runtime. Here is a first cut at it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
printf("running\n");
long long size = atoi(argv[1]);
printf("%lld\n", size);
int myArray[size];
printf("allocated array\n");
for (long long i = 0; i< size; i++) {
myArray[i] = 1;
}
printf("Done");
}
My issue is that this segfaults.
>./a.out 100000000
running
100000000
Segmentation fault: 11
I think I have to do a malloc to get this working, but I can't quite get it right.
Upvotes: 0
Views: 201
Reputation: 119
there are two suggestions:
Upvotes: 1
Reputation: 121397
There's no portable way to detect the failure of automatic allocation. On linux, you could check it by using ulimit -s
and set it to unlimited: ulimit -s unlimited
.
But even this doesn't tell you whether such a large allocation was successful. Safer way is to use dynamic allocation using malloc()
and check if allocation was successful:
int *myArray = malloc( size * sizeof *myarray);
if(!myarray) { /* allocation failed */}
Upvotes: 1