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

新手C语言问题:随机数组末尾偶尔出现超界值,求排查

问题分析与修复:C语言随机数组异常问题

核心错误点

  1. 数组越界访问
    你在打印数组的循环里犯了下标越界的错误:

    • 正向循环条件写成了x<=size,但数组下标范围是0到size-1,ptr[size]属于malloc分配内存之外的区域,里面的数值是随机垃圾值,这就是你看到偶尔出现大于1000数值的原因。
    • 反向循环起始值是x=size,同样访问了越界的内存位置。
      另外,数组不需要NULL终止符,那是C字符串的要求,和这个问题无关。
  2. 随机数生成宏逻辑错误
    你定义的Random(high, low)宏,当前逻辑是(rand() % (high - low)) + low,当调用Random(1000,1)时,high-low=999,rand()%999会生成0到998的数,加1后得到1到999,永远生成不了1000,不符合你“不大于1000”的需求(应该是包含1000)。正确写法需要让取模范围包含high-low+1,才能覆盖low到high的闭区间。

修复后的代码

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

// 修复随机数宏,生成[low, high]区间的随机数
#define Random(high, low) (rand() % (high - low + 1)) + low
int * GetArray(int);

int main()
{
    srand(time(NULL)); 
    int num = Random(15, 5);
    GetArray(num);

    return 0;
}

int * GetArray(int size){
    int* ptr = (int*)malloc(size * sizeof(int));
    for(int x = 0; x < size; x++){
        ptr[x] = Random(1000, 1);
    }
    printf(" Forward: ");
    // 修正循环条件,避免越界
    for (int x=0; x < size; x++){
        printf("a[%d]=%d  ", x, ptr[x]);
    }
    printf("\nBackward: ");
    // 修正反向循环起始值为size-1
    for (int x = size - 1; x >= 0 ; x--){
         printf("a[%d]=%d  ", x, ptr[x]);
    }
    // 释放malloc分配的内存,避免内存泄漏
    free(ptr);
    return ptr;
}

额外提醒:原代码中malloc分配的内存没有释放,长期运行会导致内存泄漏,修复后的代码补充了free(ptr)操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:05:58