how to set array size of 20 mbs in C

c

Solution

`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.

Problem

How do I create an `int` array of size 20 MB? Do I have to use `malloc` or `sbrk` or something else?

Original source