我正在阅读“hacking, The Art of Exploitation”一书,这个代码示例真的让我很困惑。
它在全局变量范围的上下文中:
#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.
}
}
这是输出:
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 $
问题是,为什么[in function] var = 5
保持稳定?我们定义var++;
了以及static_var++;
在局部函数内。怎么了?