C Calling convention and stack - Coddicted

C Calling convention and stack

The formal arguments and local variables are defined inside a function are created at a place in memory called ‘stack’.When the control returns from the function the stack is cleaned up either by the ‘Calling function’ or by the ‘Called function’, which would do this is decided by the calling convention.
Standard calling convention in C
The arguments are passed to a function in right to left order and the stack is cleaned up by the called function
Example 1. 
int a = 1;
printf(“%d %d %d”, a, ++a, a++);
output:
3 3 1
Example 2.
void main()
{
int *j;
int *fun();
j=fun();
/* 1 –> */ //printf(“Hello”);
printf(“\n %d”, *j);
}
int *fun()
{
int k=35;
return (&k);
}
output :
a. 35
b. If comment 1 (/* 1 –> */ //) is removed then output will be garbage value.
Reason
  1. In the first case (i.e. output a), when the control returned from the fun(), though k went dead but it was still left on the stack. We then accessed this value using its address that was collected in j.
  2. In the second case (i.e. output b), when we precede the call to printf() by a call to any other function, the stack is now changed, hence we get the garbage value.
All variable that are defined inside a function are normally created on the stack each time the function is called. These variables die as soon as control goes back from the function.However, if the variables inside the function are defined as static then they do not get created on stack.Instead they are created in a place in memory called “Data Segment” such variables die only when the program execution comes to an end.
 -> Formal arguments and local variables are created on stack and static variables are created on “Data segment”.

Back To Top
Rate this post

Leave a Reply