Memory Segment Whenever U create a program and load it on a CPU ie executing UR program. It loads a Process Page on the virtual memory of UR system.That Process page will be mapped to UR Task Struct which will be in UR Process Control Block PCB. Ps: Stack Segment and Heap Segment may grow other way too (UP and Down respectively)as it depend on the system U work Intel/Windows Stack grows Upwards Sparc/Solaris Stack grows Downwards When a program is executed a Function Stack Frame is created in the Stack segment of UR Process Page for each and every function called and destroyed when U exit from the function scope. Function Stack Frame All Task structs have two Pointer called the Stack Pointer (SP), and the Frame (FP) or Base Pointer (BP). SP always points to the "top" of the stack, and FP always points to the "top" of the frame. So when function are called inside functions the stack keeps growing downward. when Functions are called: Saves local variables and temporaries The fn called pushes the parameters of the fn to be called into the stack The Program counter is saved as “return address” SP pointing to previous stack is copied to the new FP In a small program like : Code: void fn (void) { int j; return; } int main (void) { int i; fn(); return 0; } The Stack frame for this program would be: To test these we can write a small Program: Code: #include <iostream> using namespace std; void fn(void) { int * ptr; ptr = (int *)&ptr; ++ptr; int* mainfp = (int*)(*ptr); --mainfp; --mainfp; *mainfp = 20; return; } int main (void) { int i = 10; fn(); cout<<”I =<<i<<endl; return 0; } Ps : This program works with Ubuntu linux. Try it for windows or sun sparc.
For those using Intel/Windows m/c Try this void fn(void) { int *ptr; ptr = (int *)&ptr; ++ptr; ++ptr; int* mnptr = (int *) *ptr; --mnptr; --mnptr; *ptr = 300; return; }
Hi Guys , Sorry that i missed one Infor about the stack frame. The stack frame would be like ____________________________ |_______Local Variables_______ | |________Padding____________ | |______Frame Pointer_________ | |______Return Address________ | |_Arguments/saved Temporaries_| So to calculate padding = if ((Total size of local variables)% or mod 8) then padding = 4 else padding = 0; so when You need to calculate Total size of a Stack frame : Size of all parameter + sizeof RA+ sizeofFP + Padding + sizeof Local In the example Code: void fn(void) { int *ptr; ptr = (int *)&ptr; ++ptr; //Points to padding memory. ++ptr; //points to FP where is stores previous FP int* mnptr = (int *) *ptr; --mnptr; //points to Padding memof Main fn --mnptr; //points to Local variable. *ptr = 300; return; } int main(void) { int i = 0; fn(); cout<<"I ="<<i<<endl; return 0; }