Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't allocate more than a million integers

Tags:

c

I'm trying to time and compare sorting algorithms. From what I understand: sizeof(int) is 4 bytes, therefore int array[one million]; yields (4) million bytes which is 4,000 kb or 4mb roughly.

So why can't I? I'm pretty sure I have more. 2gb to be precise.

I'm using gcc if that means anything.

like image 802
lightburst Avatar asked Nov 13 '11 12:11

lightburst


3 Answers

You can't have that many integers on stack.

Try allocating space on heap for your array.

int *array = malloc(1000000*sizeof(int));
// if array is not null, then you have an array with 1,000,000 ints.

After you are done with your sorting algorithms, you free the array:

free(array); // frees memory allocated before
like image 70
Pablo Santa Cruz Avatar answered Nov 08 '22 15:11

Pablo Santa Cruz


It's likely you are trying to allocate it on the stack, which is small.

  • Make the array static or global (same thing really, but with different visibility)

    static int arr[...]
    
  • Use malloc

    int *p = malloc(... * sizeof *p);
    
like image 4
cnicutar Avatar answered Nov 08 '22 13:11

cnicutar


The statement

int array[one million];

declares and stores your array on the Stack. The size of your program's stack is pretty small, and cannot contain 1 million ints. Instead, what you should do, is declare the array on the Heap. For that, create a pointer to the array and use the malloc() function to allocate memory. This way, the memory is allocated on the heap, and you have way more memory for utilisation.

int *arrayName = malloc(1000000*sizeof(int));

You should always check the pointer for the value returned, since the malloc may fail, and it will return a NULL value. If you try to access such a pointer, your program will terminate abruptly. So make sure, to check for correct allocation.

Also, always remember to

free(arrayName);

when you are done using the array. Else, it may lead to a memory leak, in a certain more complex programs.

For a better understanding of Stacks and Heaps, refer to this Question: What and where are the stack and heap?

like image 2
darnir Avatar answered Nov 08 '22 13:11

darnir