Skip to content

Instantly share code, notes, and snippets.

@itczl22
Last active November 5, 2016 07:51

Revisions

  1. itczl22 revised this gist Nov 5, 2016. No changes.
  2. itczl22 created this gist Nov 1, 2016.
    32 changes: 32 additions & 0 deletions stack-growth-direction.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    /*
    * 判断栈的增长方向
    *
    * 系统在调用函数时, 这个函数的相关信息都会出现栈之中, 比如参数、返回地址和局部变量
    * 入栈顺序和函数内的变量申明顺序可能不一样, 这和编译器有一定的关系
    * 所以不能通过一个函数内的多个变量在栈中的地址来判断栈的增长方向
    *
    * 当它调用另一个函数时, 在它栈信息保持不变的情况下会把它调用那个函数的信息放到栈中
    * 两个函数的相关信息位置是固定的, 肯定是先调用的函数其信息先入栈, 后调用的函数其信息后入栈
    * 这样通过函数栈来确定栈的增长顺序
    */
    #include <stdio.h>

    void func_2nd(int* val_1st) {
    int val_2nd = 20;
    printf("%p\n%p\n", val_1st, &val_2nd);
    if(val_1st > &val_2nd) {
    printf("从高到低增长\n");
    } else {
    printf("从低到高增长\n");
    }
    }

    void func_1st(void) {
    int val_1st = 10;
    func_2nd(&val_1st);
    }

    int main(void) {
    func_1st();
    return 0;
    }