26.07.2018 Views

hacking-the-art-of-exploitation

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

0x267<br />

Variable Scoping<br />

Ano<strong>the</strong>r interesting concept regarding memory in C is variable scoping or<br />

context—in p<strong>art</strong>icular, <strong>the</strong> contexts <strong>of</strong> variables within functions. Each function<br />

has its own set <strong>of</strong> local variables, which are independent <strong>of</strong> everything<br />

else. In fact, multiple calls to <strong>the</strong> same function all have <strong>the</strong>ir own contexts.<br />

You can use <strong>the</strong> printf() function with format strings to quickly explore this;<br />

check it out in scope.c.<br />

scope.c<br />

#include <br />

void func3() {<br />

int i = 11;<br />

printf("\t\t\t[in func3] i = %d\n", i);<br />

}<br />

void func2() {<br />

int i = 7;<br />

printf("\t\t[in func2] i = %d\n", i);<br />

func3();<br />

printf("\t\t[back in func2] i = %d\n", i);<br />

}<br />

void func1() {<br />

int i = 5;<br />

printf("\t[in func1] i = %d\n", i);<br />

func2();<br />

printf("\t[back in func1] i = %d\n", i);<br />

}<br />

int main() {<br />

int i = 3;<br />

printf("[in main] i = %d\n", i);<br />

func1();<br />

printf("[back in main] i = %d\n", i);<br />

}<br />

The output <strong>of</strong> this simple program demonstrates nested function calls.<br />

reader@<strong>hacking</strong>:~/booksrc $ gcc scope.c<br />

reader@<strong>hacking</strong>:~/booksrc $ ./a.out<br />

[in main] i = 3<br />

[in func1] i = 5<br />

[in func2] i = 7<br />

[in func3] i = 11<br />

[back in func2] i = 7<br />

[back in func1] i = 5<br />

[back in main] i = 3<br />

reader@<strong>hacking</strong>:~/booksrc $<br />

62 0x200

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!