Linux栈空间及栈地址方向

写了个简单程序,可以让linux的栈空间耗尽,然后出现core dumped,即栈溢出

代码如下:

#include <stdio.h>void overFlow(){long i;printf("&i : %p\n",&i);overFlow();}int main(){ overFlow();}

运行程序 ./out > out.log

栈地址是从高到低,所以用第一个减去最后一个地址,,就能得到栈空间

我用python算出

$python

>>> (0x7fffe4c974cc – 0x7fffe449be2c)*1.0/1024/10247.982086181640625

可见是8M

使用ulimit -s可得到8192, 与程序结果一致

overFlow如下填写也能core dumped

void overFlow(){char i0[1024*1024*2] = {0};char i1[1024*1024*2] = {0};char i2[1024*1024*2] = {0};char i3[1024*1024*2] = {0};char i[1024*1024*2] = {0};printf("&i : %p\n",&i);}

此外,说下局部变量入栈的顺序,代码:

int main(){    int a;    char s1[1024] = {0};    char s2[1024] = {0};    char ch1;    char ch2;    char* p1, *p2;    int b, c, d, e ,f;    printf("&a: %p\n",&a);    printf("&s1: %p\n",s1);    printf("&s2: %p\n",s2);    printf("&ch1: %p\n",&ch1);    printf("&ch2: %p\n",&ch2);    printf("&p1: %p\n",&p1);    printf("&p2: %p\n",&p2);    printf("&b: %p\n",&b);    printf("&c: %p\n",&c);    printf("&d: %p\n",&d);    printf("&e: %p\n",&e);    printf("&f: %p\n",&f);}

该代码在不同的平台有不同的顺序,故不探讨了

判断栈的增长方向:

#include <iostream>void findStackDirection(){    static int* addr = NULL;    int dummy;    if(addr == NULL)    {        addr = &dummy;        findStackDirection();    }    else    {       if(&dummy > addr)       {           std::cout << "STACK direction: Low -> High" << std::endl;       }       else       {           std::cout << "STACK direction: High -> low" << std::endl;       }    }}void func(int a, int b){    if(&b < &a)    {        std::cout << "ARGS: left -> right" << std::endl;    }    else    {        std::cout << "ARGS: right -> left" << std::endl;    }} int main(){    findStackDirection();    func(1,2);}我的工作系统linux输出为

STACK direction: High -> lowARGS: left -> right

使用在线编译输出为

STACK direction: High -> lowARGS: right -> left

可以得出

1. 栈的增长方向均为High -> low

2. 不同的系统参数入栈顺序可能不同,我的工作系统linux上是从左至右,而网上编译器是从右至左

大把大把的时光从指缝间遛走,

Linux栈空间及栈地址方向

相关文章:

你感兴趣的文章:

标签云: