Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When memory is allocated to a function (definition or call)

Tags:

c++

c

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?

  • when is defined (line 2) (compile time)
  • or when function is called (line 8)(run time)

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!

like image 741
Anil Bhaskar Avatar asked Mar 09 '15 13:03

Anil Bhaskar


2 Answers

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.

like image 161
Vlad from Moscow Avatar answered Sep 30 '22 14:09

Vlad from Moscow


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.

like image 31
Lundin Avatar answered Sep 30 '22 14:09

Lundin