Memory allocation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Memory allocation

if I write a code like this #include<iostream> using namespace std; int main() { int x; cin>>x; int a[x]; } then how much memory will allocate during COMPILATION as we knew that arry's memory will allocate during compilation but in this case user give a number then memory will allocate and moreover how it is different to dynamic memory allocation???

24th Feb 2017, 6:26 AM
SHIV DADHANIA
SHIV DADHANIA - avatar
1 Answer
+ 3
Memory isn't allocated during compilation. It is allocated at runtime. You're confusing the difference between defining memory needs and allocation. We can define our memory needs by calculating the amount of memory our predefined variables and classes will take based upon their type which can be calculated or approximated prior to compilation. Allocation is when the running program actually goes about the process of delegating the space within memory and blocking it off for the variable/class of that type, to ensure that the needed amount is available. int x; // This is standard allocation and memory is allocated when the program is started due to its size being predetermined and fixed. int arr[x]; // Is actually a form of dynamic allocation. When the program starts, a place in memory is allocated like the variable above, but just to hold the pointer for the array as this has a predetermined fixed size. When this line of code is reached within the program at runtime and the value of x has been determined the array is dynamically allocated in memory and the pointer value is updated in memory.
24th Feb 2017, 6:59 AM
ChaoticDawg
ChaoticDawg - avatar