为这个疑问着迷。想弄清楚,参考了http://blog.sina.com.cn/s/blog_a0e859400101279a.html。
/*
* find_stack_direction.c
* To find the growing direction of stack and
* to recognize the pattern of data storage of the computer.
*/
#include <stdio.h>
static int stack_dir;
void find_stack_direction (void);
int main (void){
if (1 == stack_dir){
puts ("stack grew upward.");
}
else{
puts ("stack grew downward.");
}
//little-endian or big-endian?
{
int a = 1;
if (*(char *)&a == 1){
puts ("Little-Eidian.");
}
else{
puts ("Big-Endian.");
}
}
return 0;
}
void find_stack_direction (void){
static char * addr = NULL;
char dummy;
if (NULL == addr){
addr = &dummy;
find_stack_direction ();
}
else{
if (addr > &dummy){ // upwards
stack_dir = 1;
}
else{ // downwards
stack_dir = -1;
}
}
}
结果:
stack grew download.
Little-Eidian.
仔细想想,其实不需要递归了。很随意的也可以,只要比较caller和callee的非静态局部变量地址大小就ok了。
#include <stdio.h>
char * p = (char *)0x7FFFFFFF;
void f ();
void main (){
char b;
p = &b;
f ();
}
void f (){
char a;
if ( &a > p)
puts ("stack grew upward.");
else
puts ("stack grew downward.");
}
结果:
stack grew downward.
更简练的代码可以这样(不过不推荐这样写,因为返回了局部变量的地址不安全,不过对于这个测试来说无妨)。
#include <stdio.h>
char * b (char c){
return &c;
}
void main (){
char a;
if (&a < b (a))
puts ("stack grew upward.");
else
puts ("stack grew downward.");
}