How do I create an int array of size 20 MB?
Do I have to use malloc or sbrk or something else?
malloc is usually a good idea if you want something like 20MB. Most stacks are smaller and will crash the program if you try.
int *myInts = (int *)malloc(20*1024*1024);
or place it as a static/global variable:
int myArray[20*1024*1024/sizeof(int)];
or with sbrk
int *myInt = sbrk(0); /* Get the current pointer */
sbrk(20*1024*1024); /* Now increase it */
But as the man page says "avoid using sbrk". The only time you should be using sbrk is if you are implementing your own memory allocator.
I think your best choice is using malloc, for example:
#include stdio.h
#include malloc.h
int main() {
int array_size = 0;
int* my_array = (int*)malloc(array_size);
free((void*)my_array);
return 0;
}
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