春暖花开

局部变量的栈溢出

先上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
const int MAX_N = 10000000;
using namespace std;
bool Tree[MAX_N] = {false};//全局变量
int main(){
int depth, balls;
cin >> depth >> balls;
int ind = 0;
int last = 0;
while( ind ++ < balls ){
int curr = 1;
for ( int i = 0; i < depth; ++i ){
if( false == Tree[curr] ){
curr = curr*2;
}
else{
curr = curr*2 + 1;
}
Tree[curr] = !Tree[curr];
last = curr;
}
}
cout << last << endl;
return 0;
}

代码1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>
const int MAX_N = 10000000;
using namespace std;
bool Tree[MAX_N] = {false};
int main(){
int depth, balls;
cin >> depth >> balls;
bool Tree[MAX_N] = {false};//局部变量
int ind = 0;
int last = 0;
while( ind ++ < balls ){
int curr = 1;
for ( int i = 0; i < depth; ++i ){
if( false == Tree[curr] ){
curr = curr*2;
}
else{
curr = curr*2 + 1;
}
Tree[curr] = !Tree[curr];
last = curr;
}
}
cout << last << endl;
return 0;
}

代码2

观察代码1代码2,二者只有一个区别,前者Tree为全局变量,而后者为局部变量。一般来说,我们可能觉得两个函数运行的时候不会有什么不同,然而却出现不同的结果:

代码1能正确运行,代码2

惊喜不惊喜,意外不意外!

我们知道,在内存中,全局变量存于全局变量区,而局部变量位于栈中,函数以栈帧的形式存储。相对来说,全局变量区空间较大,而栈空间较小,因此便导致了代码2的栈溢出,而代码1则正常。

0%