Stack Memory 2 (also called Call Stack) Yung-Hsiang Lu Purdue University
When a function is called, the line number after the call is stored in the stack memory.
Arguments in Function Call When a function is called with one (or several) argument, the argument is stored (pushed) to the stack memory. 1 void f1(int x) 2 { 3 int a; 4 a = f2(7); 5 x = a + 5; 6 ... 7 } 8 int f2(int y) 9 10 y = 7 line 5
Arguments in Function Call When a function is called with one (or several) argument, the argument is stored (pushed) to the stack memory. 1 void f1(int x) 2 { 3 int a; 4 a = f3(7, 3.2); 5 x = a + 5; 6 ... 7 } 8 int f3(int y, double z) 10 z = 3.2 y = 7 line 5
How to write good code? Make each function's behavior depends on only the input arguments and nothing else. The function has no static variable. The program has no global variable. Read "Global Variables Considered Harmful" by Wulf in 1973.
When a function is called, the statement after the call is stored in the stack memory. If the call has argument (or arguments), the arguments are stored in the stack memory.
The frame of a called function The return location and the arguments' values form a "frame" of the called function. 1 void f1(int x) 2 { 3 int a; 4 a = f3(7, 3.2); 5 x = a + 5; 6 ... 7 } 8 int f3(int y, double z) 9 10 Frame of f3 z = 3.2 y = 7 line 5
Local Variables A function's local variables are also stored in the frame. If a function has several local variables, all of them are stored in the frame. 1 void f1(int x) 2 { 3 int a; 4 a = f3(7, 3.2); 5 x = a + 5; 6 ... 7 } 8 int f3(int y, double z) 9 10 int b = y + 3; Frame of f3 b = 10 z = 3.2 y = 7 line 5
Stack Memory may store three things: return location arguments local variables