When we 'define' a variable inside a function (not main here), is the memory allocation done at runtime or the loader serves for us??
And what happens when i have :
int f()
{
int a=10;
........
}
main()
{
int i;
scanf("%d",&i);
while(--i)
f();
..........
}
Is 'a' in function f() created 'i' times?? And so is it dynamic allocation??
The local variable a is made during each call of f(). It is part of setting up the 'stack-frame' for f() and costs (almost) nothing in time. It eats up a little stackspace, but no more than is necessary for an int.
During while(--i) f(); the function f() is called 10 times and each time a 'new' a occupies the same spot of memory. We do not call this dynamic allocation, it is called stack, local or auto allocation.
This is a stack allocation, meaning that place is reserved on the stack for the integer - it's not allocated like "find 4 free bytes on the heap and allocate them for me".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With