Large array allocation (5000+)

I am working on an application, there were three possible sizes for the data entered:

  • small: 1000 elements
  • medium = 5000 elements
  • large = 500,000 items

The problem is that I cannot allocate a large array. It seems that a size larger than 5000 is not accepted.

I get a runtime error when I do the following:

long size=1000; char ch; int arr[size]; ch=getch(); if(ch==..) size=...; 

Sizes 1000 and 5000 seem to work fine, but how can I make an array of size 500k this way?

+7
source share
3 answers

Your stack cannot store so much data. You should allocate large arrays on the heap as follows:

 int *array = malloc (sizeof(int)*size); 

As indicated on Friday, be sure to free your memory as soon as you're done.

 free(array); 
+8
source

You can allocate such an array on the heap:

 int *arr; arr = malloc (sizeof(int) * 500000); 

Remember to verify that the selection is complete (if not, malloc returns NULL).

And as mentioned in pmg - since this array is not on the stack, you should free it after you have finished working with it.

+8
source

It is too big for the stack. Instead, you need to allocate it on the heap using malloc.

+3
source

All Articles