Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set array size of 20 mbs in C [closed]

Tags:

c

How do I create an int array of size 20 MB?

Do I have to use malloc or sbrk or something else?

like image 735
Nabmeister Avatar asked Dec 05 '25 04:12

Nabmeister


2 Answers

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.

like image 77
Gille Avatar answered Dec 07 '25 19:12

Gille


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;
}