Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1
Programming 63

In each function, the variable i is set to a different value and printed.


Notice that within the main() function, the variable i is 3, even after calling


func1() where the variable i is 5. Similarly, within func1() the variable i


remains 5, even after calling func2() where i is 7, and so forth. The best


way to think of this is that each function call has its own version of the


variable i.


Variables can also have a global scope, which means they will persist


across all functions. Variables are global if they are defined at the beginning


of the code, outside of any functions. In the scope2.c example code shown


below, the variable j is declared globally and set to 42. This variable can be


read from and written to by any function, and the changes to it will persist


between functions.


scope2.c


#include <stdio.h>


int j = 42; // j is a global variable.


void func3() {
int i = 11, j = 999; // Here, j is a local variable of func3().
printf("\t\t\t[in func3] i = %d, j = %d\n", i, j);
}


void func2() {
int i = 7;
printf("\t\t[in func2] i = %d, j = %d\n", i, j);
printf("\t\t[in func2] setting j = 1337\n");
j = 1337; // Writing to j
func3();
printf("\t\t[back in func2] i = %d, j = %d\n", i, j);
}


void func1() {
int i = 5;
printf("\t[in func1] i = %d, j = %d\n", i, j);
func2();
printf("\t[back in func1] i = %d, j = %d\n", i, j);
}


int main() {
int i = 3;
printf("[in main] i = %d, j = %d\n", i, j);
func1();
printf("[back in main] i = %d, j = %d\n", i, j);
}


The results of compiling and executing scope2.c are as follows.


reader@hacking:~/booksrc $ gcc scope2.c
reader@hacking:~/booksrc $ ./a.out
[in main] i = 3, j = 42

Free download pdf