hawkeye
hawkeye

Reputation: 35702

C - creating an array at runtime with size greater than 10M

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

Answers (2)

Nibnat
Nibnat

Reputation: 119

there are two suggestions:

  1. write a function which receives a argument which is INT(or which type you want) type,then you can put a value to it when running,and then ,you can do your thing.
  2. try malloc.

Upvotes: 1

P.P
P.P

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

Related Questions