20191204调用函数申请的栈空间注意事项

要避免栈空间溢出。
当调用一个函数时,就会在栈空间,为这个函数,分配一块内存区域,
这块内存区域,专门给这个函数使用。
这块内存区域,就叫做“栈帧”。
每调用一次函数,就申请一次栈幀。
循环调用时,注意是否会出现栈空间爆掉的情况。

#include<Windows.h>
#include<iostream>
#include<stdio.h>
using namespace std;

void test(int n) {
	char buf[1024 * 100];//100k
	cout << "n=" << n<<endl;
	printf_s("buf:%X\n", buf);
	if (n == 1) {
		return ;
	}
	test(n - 1);
}

int main() {
	test(20);

	system("pause");
	return 0;
}

运行结果如下,当调用9次后,栈空间爆掉了,出现stack溢出的错误。
经过计算,默认的栈帧空间大小为1.4M,当循环调用函数占用栈空间时,溢出就会报错!
在这里插入图片描述

发布了51 篇原创文章 · 获赞 0 · 访问量 560

猜你喜欢

转载自blog.csdn.net/weixin_40071289/article/details/103390190