You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行时检查失败2:变量'arr'周围栈损坏,递归求斐波那契数异常

问题分析与修复

你的代码触发栈损坏错误的核心原因是数组越界访问,具体问题出在递归函数的终止条件上:

  • 你定义的数组arr[SIZE]下标范围是0到39(因为SIZE=40,数组下标从0开始计数)
  • 当前终止条件if (offset > SIZE)意味着当offset等于40时,仍然会执行arr[offset] = arr[n1] + arr[n2];,此时访问arr[40]已经超出数组的合法范围,直接破坏了栈内存结构

修复后的代码

把递归函数的终止条件改成offset >= SIZE即可,这样当offset等于40时会直接返回,避免越界访问:

#include <stdio.h>
#define SIZE 40
void sum(int arr[], int n1, int n2, int offset);

int main(void)
{
    int arr[SIZE] = { 0, 1 };

    printf("%d\n", arr[0]);
    printf("%d\n", arr[1]);
    sum(arr, 0, 1, 2);

    return 0;
}
void sum(int arr[], int n1, int n2, int offset)
{
    if (offset >= SIZE)
        return;

    arr[offset] = arr[n1] + arr[n2];
    printf("%d\n", arr[offset]);
    sum(arr, n1 + 1, n2 + 1, offset + 1);
}

额外说明

  • 原代码中,offset从2开始递增,直到40时仍会执行赋值操作,arr[40]属于数组之外的栈内存区域,写入该区域会破坏栈上的其他数据,最终在return 0;时触发栈损坏检测
  • 修复后,递归会在offset等于40时停止,刚好覆盖前40个斐波那契数(下标0到39)

内容的提问来源于stack exchange,提问作者motabon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 02:36:18