Cannot allocate more than a million integers

I am trying to compare time and compare sorting algorithms. From what I understand: sizeof(int) is 4 bytes, so int array[one million]; yields (4) million bytes, which is approximately 4,000 kilobytes or 4 MB.

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

I use gcc if that means anything.

+6
source share
4 answers

You cannot have as many integers on the stack.

Try allocating heap space 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 executing your sorting algorithms, you will free the array:

 free(array); // frees memory allocated before 
+8
source

You are probably trying to allocate it on the stack, which is not enough.

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

     static int arr[...] 
  • Use malloc

     int *p = malloc(... * sizeof *p); 
+4
source

Statement

 int array[one million]; 

declares and saves your array on the stack. The size of your program stack is quite small and cannot contain 1 million Ints. Instead, what you should do is declare an array on the heap. To do this, create a pointer to an array and use the malloc () function to allocate memory. That way, memory is allocated on the heap, and you have more memory to use.

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

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

Also, always remember

 free(arrayName); 

when you finish using the array. In addition, this may lead to a memory leak in some more complex programs.

For a better understanding of stacks and heaps, see this question: What and where is the stack and heap?

+2
source

It is highly recommended that huge variables be sent to the heap via malloc or new . But you can still have such a large array on the stack, increasing the size of the stack. This is often necessary when you can have extremely deep recursion.

Linux / gcc has a default size of 8 MB for the stack, while Windows has 1 MB. The stack size can be increased by adjusting the linker or binary settings.

[EDITED] For example, you can increase the size of the stack in gcc:

gcc -Wl,--stack,16777216 hello.c (This is only for MigW / cygwin gcc on Windows)

So, the stack will be 16 MB.

In addition, the stack size can be changed with the ulimit command, like (this is the easiest way on Linux):

ulimit -s 16777216

Note that ulimit -s will provide you with the current stack size.

Finally, you can call setrlimit in your program.

0
source

Source: https://habr.com/ru/post/901377/


All Articles