I’m reading “hacking, The Art of Exploitation” book, and this code sample really confuses me.
It’s within the context of Global Variable Scope:
#include <stdio.h>
void function() { // An example function, with its own context
int var = 5;
static int static_var = 5; // Static variable initialization
printf("\t[in function] var = %d\n", var);
printf("\t[in function] static_var = %d\n", static_var);
var++; // Add one to var.
static_var++; // Add one to static_var.
}
int main() { // The main function, with its own context
int i;
static int static_var = 1337; // Another static, in a different context
for(i=0; i < 5; i++) { // Loop 5 times.
printf("[in main] static_var = %d\n", static_var);
function(); // Call the function.
}
}
And here is the output:
reader@hacking:~/booksrc $ gcc static.c
reader@hacking:~/booksrc $ ./a.out
[in main] static_var = 1337
[in function] var = 5
[in function] static_var = 5
[in main] static_var = 1337
[in function] var = 5
[in function] static_var = 6
[in main] static_var = 1337
[in function] var = 5
[in function] static_var = 7
[in main] static_var = 1337
[in function] var = 5
[in function] static_var = 8
[in main] static_var = 1337
[in function] var = 5
[in function] static_var = 9
reader@hacking:~/booksrc $
The question is that, WHY [in function] var = 5 remains steady? We defined var++; as well as static_var++; within the local function. What is happening?
This is precisely what distinguishes a static variable from a non-static one. A static variable has static-storage-duration, meaning the variable stays alive during the run of the program. Non-static variables have automatic storage duration; meaning it will disappear at the end of the scope in which it was created (in this case, at the end of
function). When the variable is disposed of, the next time the function is invoked, a new instance of that variable will be created.