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.
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
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);
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With