When the memory is allocated to a function. For example:
int doubleMe(int smthng){
int dbl = 2*smthng; //line 2
return dbl;
}
void main(){
int var;
printf("The double of var is: %d",doubleMe(var)); //line 8
}
When is memory allocated to variable dbl
?
I believe it is allocated when function is called(run-time) in stack. And freed when function exits, is it? Would be great if someone could please explain it better.
This question looks similar but not quite!
The compiler generates object code of a function when it is defined. The generated code contains instructions to allocate memory in the stack for function local variables or it can use registers to accomodate them.
Where a function is called the compiler generates object code of the function call and corresponding instructions to push arguments on the stack. At this point the compiler may not to know how the function is defined and whether it is defined because its definition can be in some other module or library.
Take into account that the compiler may inline functions even if you yourself do not use function specifier inline
. In this case it will place the function definition in the point where the function is called.
Memory is allocated to variable dbl(or var) at compile time in the stack memory
Not correct, it is allocated in run-time, just as all other stack variables. That's the whole point of using a stack. It is allocated when your function is called, in run-time.
I believe it is allocated when function is called. And freed when function exits, is it?
Yes.
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