堆栈溢出的常见情况

来源:互联网 发布:剑灵克劳德捏脸数据 编辑:程序博客网 时间:2024/06/06 09:21

一、局部数组过大。当函数内部的数组过大时,有可能导致堆栈溢出。

例如:

#include <stdio.h>#define SIZE 1 * 1024 * 1024int main(){int b[SIZE];int i;for(i = 0; i < SIZE; ++i){b[i] = i;}for(i = 0; i < SIZE; ++i){printf("%d", b[i]);}return 0;}

二、递归调用层次太多。递归函数在运行时会执行压栈操作,当压栈次数太多时,也会导致堆栈溢出。

#include <stdio.h>int Sum(const unsigned int n){printf("now n is %u\n", n);if(0 == n || 1 == n){return n;}return n + Sum(n - 1);}int main(){unsigned int n;printf("Input n: ");scanf("%d", &n);printf("The sum of 1 to %u is %u\n", n, Sum(n));return 0;}

三、指针或数组越界。这种情况最常见,例如进行字符串拷贝,或处理用户输入等等。

四、没有垃圾回收。


0 0
原创粉丝点击