C language, a way to get the direction of stack growth

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.