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

LeetCode求解数组前缀和时遇内存越界运行时错误求助

运行时错误分析与修复:前缀和数组问题

运行时错误信息

Line 9: Char 22: runtime error: store to address 0x7fff41648ec4 with insufficient space for an object of type 'int' [solution.c]
0x7fff41648ec4: note: pointer points here
01 00 00 00 70 60 00 00  c7 4f e5 06 29 7f 00 00  10 90 64 41 ff 7f 00 00  60 95 e8 06 29 7f 00 00
^

题目描述

给定数组nums,定义前缀和数组runningSum满足runningSum[i] = sum(nums[0]…nums[i]),返回该前缀和数组。

示例

  • 示例1
    • 输入:nums = [1,2,3,4]
    • 输出:[1,3,6,10]
    • 解释:前缀和计算逻辑为[1, 1+2, 1+2+3, 1+2+3+4]
  • 示例2
    • 输入:nums = [1,1,1,1,1]
    • 输出:[1,2,3,4,5]
    • 解释:前缀和计算逻辑为[1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]
  • 示例3
    • 输入:nums = [3,1,2,10,1]
    • 输出:[3,4,6,16,17]

你的错误代码

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* runningSum(int* nums, int numsSize, int* returnSize){
    if(numsSize>=1){
        returnSize[0]=nums[0];
    }
    for(int i=1;i<numsSize;i++){
        returnSize[i]=returnSize[i-1]+nums[i];
    }
    return returnSize;
}

错误原因

你完全搞错了returnSize的用途:

  • returnSize是一个指针,仅用来传递返回数组的长度,不是存储前缀和的容器。它指向的空间通常只有1个int的大小,用来存放你要返回的数组的元素个数。
  • 你直接往returnSize的地址写入多个int值,当i≥1时,returnSize[i]属于越界访问,写入了不属于你的内存空间,触发了运行时内存错误。

正确代码

按照题目要求,你需要手动分配一块能容纳numsSize个int的内存来存储前缀和,把数组长度赋值给*returnSize,最后返回这块内存的指针:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* runningSum(int* nums, int numsSize, int* returnSize){
    // 设置返回数组的长度
    *returnSize = numsSize;
    // 分配足够内存存储前缀和数组
    int* result = (int*)malloc(numsSize * sizeof(int));
    if (result == NULL) {
        // 内存分配失败时,返回长度0和NULL
        *returnSize = 0;
        return NULL;
    }
    // 计算前缀和
    result[0] = nums[0];
    for(int i=1; i<numsSize; i++){
        result[i] = result[i-1] + nums[i];
    }
    return result;
}

注意事项

  • 必须检查malloc的返回值,避免内存分配失败导致后续错误。
  • 题目注释明确说明调用者会负责free返回的数组,无需在函数内释放。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:27:33