Reprint: http://blog.chinaunix.net/uid-2413049-id-109836.html
In the process of reading wget source code, we find a clever way to achieve the stack growth direction with C language.
wget version is 1.11.4
Implementation code:
static void find_stack_direction () { static char *addr = NULL; /* Address of first ' dummy ', once known. */ Auto Char dummy; /* To get stack address. */
if (addr = = NULL) {/* Initial entry. */ addr = address_function (dummy);
find_stack_direction (); /* Recurse once. */ } Else { / * Second entry. */ if (address_function (dummy) > Addr) Stack_dir = 1; /* Stack grew upward. */ Else Stack_dir =-1; /* Stack grew downward. */ } } |
Simplified correlation definition:
static int stack_dir; /* 1 or-1 once known. */
#define Address_function (ARG) & (ARG) |
The method of using function recursion for find_stack_direction function
The first entry, because addr is null, assigns the address of the character variable dummy to the static variable addr
The second entry, because the static variable addr has been assigned a value, so enter "Second entry."
Next, compare the dummy address of the second entry to the dummy address of the first entry
If the value is positive, the stack grows to a high address, otherwise the stack grows to a low address
Cleverly used the idea that "function recursion also uses the stack", pretty:)
C language, a way to get the direction of stack growth