It is often said to use malloc when size is known at run time we could also write
int x;
scanf("%d",&x);
char arr[x];
so why use malloc when we can declare array on the fly.
It is often said to use malloc when size is known at run time we could also write
int x;
scanf("%d",&x);
char arr[x];
so why use malloc when we can declare array on the fly.
Writing char arr[x];
will allocate the memory on the stack.
The size of the stack is typically limited to around 1MB. You'll get runtime errors if you exceed this pre-defined amount. Some compilers will allow you to change the stack size, but you'll still hit a limit eventually of many orders of magnitude than you can get with malloc
.
VLA
[Variable length array] is a concept present in C99
onwards.
malloc()
originates much before that.
Also, malloc()
and family allocates memory from heap. It does not use the comparatively limited stack space.
OTOH, gcc
allocates space for VLA
s in the stack itself.