Use the C language to determine the orientation instance of the stack

  • 2020-05-10 18:32:34
  • OfStack

This 1 problem is mainly how to interpret the address size of successively pushed variables, such as a and b. The two variables 1 are defined after 1. If the address of a is larger than the address of b, it means that the address of a is increased in the direction of low address; otherwise, the address of b is increased in the direction of high address. When writing an C program, you cannot simply and directly define two variables to compare their address sizes, because there is a good chance that the compiler will optimize and the result will not be true. To avoid this compiler optimization situation, you can define a variable into a function and call it recursively.

For example, the following code:


#include <stdio.h>

static int stack_direction = 0;

static void FindStackDirection()
{
  static char *addr = NULL;
  auto char dummy;
  if (NULL == addr) {
    addr = &dummy;
    FindStackDirection();  // Recursive call, let dummy It's defined twice and 1 First, 1 After into the stack 
  } else {
    if (&dummy > addr) {  // The two addresses are compared and pushed back dummy If the address is larger than the previous one, it means it is growing to a higher address 
      stack_direction = 1;
    } else {
      stack_direction = -1;
    }
  }
}

int main(int argc, char const *argv[])
{
  FindStackDirection();
  if (1 == stack_direction) {
    puts("stack grew upward");
  } else {
    puts("stack grew downward");
  }

  return 0;
}

Related articles: