Linux stack space and stack address direction, linux space direction
A simple program is written to exhaust the linux stack space, and then core dumped occurs, that is, stack overflow.
The Code is as follows:
#include <stdio.h>void overFlow(){ long i; printf("&i : %p\n",&i); overFlow();}int main(){ overFlow();}
Run the program./out> out. log
Stack address is from high to low, so the stack space can be obtained by subtracting the last address from the first address.
I use python to calculate
$ Python
>>> (0x7fffe4c974cc-0x7fffe449be2c) * 1.0/1024/1024
7.982086181640625
The visible value is 8 Mb.
Use ulimit-s to get 8192, consistent with the program results
The overFlow can also be 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);}
In addition, let's talk about the sequence of local variables going into the stack. Code:
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);}
This code has different order on different platforms, so we will not discuss it.
Determine the stack growth direction:
#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);}
My work system output in linux is
STACK ction: High-> low
ARGS: left-> right
Use online compilation to output
STACK direction: High -> lowARGS: right -> left
We can conclude that
1. Stack growth direction is High-> low
2. Different system parameters may have different stack import sequence. In my operating system, linux runs from left to right, and online compilers run from right to left.