+ 2

C memory allocation function - Why???

Why to use memory allocation function of c (mallloc(), callloc() ) As size of an array can defined taken as such also - #include <stdio.h> void main(){ int n; printf("Enter n of array : "); scanf("%d", &n); int arr[n]; printf("%d", sizeof(arr)); } - This code defines the variable 'arr' of int type, and allocating size by taking user input. Then what wrong to use this then mallloc() or callloc() functions???

6th Mar 2021, 10:47 AM
AMAN GUPTA
AMAN GUPTA - avatar
3 Respostas
+ 1
By your code, you are allocating size at compile time. Its a static allocation.. if you need more allocation at run time, you need more size without altering previous data and size. that can be done by dynamic allocation functions.. malloc, calloc, .. so it has advantage of not wasting memory and extending when ever you need in simple terms..
6th Mar 2021, 11:00 AM
Jayakrishna 🇮🇳
+ 3
Using variable length arrays [ VLAs for short ] like this can be potentially dangerous, as when you do arr[n] and *n* is a large number then you will end up consuming a huge chunk of stack memory with only your array which will increase the chances of overflowing it and ultimately leading to undefined behaviour. The simple alternative is to use heap memory instead to store your array( heap memory have comparatively more space than stack ) and in order to do that, you have to use malloc(), calloc() etc.
6th Mar 2021, 11:03 AM
Arsenic
Arsenic - avatar