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

malloc分配内存后访问触发Segmentation Fault的问题咨询

段错误原因分析与修复方案

你的问题根本不是malloc分配内存失败,而是数组索引的计算完全错误。

错误点解析

当你使用nd[i * sizeof(struct node)]时,混淆了「数组下标」和「字节偏移量」的概念:

  • 数组下标代表的是元素的个数,比如nd[i]直接指向第i个struct node元素,编译器会自动帮你计算对应的字节偏移(i * sizeof(struct node))。
  • 你手动乘了sizeof(struct node),相当于把下标放大了8倍(你的struct包含两个unsigned int,总共8字节)。当i=3000时,实际访问的是nd[24000],当i增加到3045时,3045*8=24360,已经超过了你分配的24356个元素的范围,内存越界直接触发段错误。

修复后的代码

把循环里的索引改成正常的数组下标即可,同时建议添加内存分配失败检查和内存释放:

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

struct node {
    unsigned int n1;
    unsigned int n2;
};

int main() {
    struct node *nd = (struct node *)malloc(24356 * sizeof(struct node));
    if (nd == NULL) {
        perror("malloc failed");
        return 1;
    }
    for(int i=0; i < 24356; i++) {
        nd[i].n1 = i;
        nd[i].n2 = i+1;
    }       
    free(nd);
    return 0;
}

关于malloc的补充

190KB属于极小的内存分配量,现代系统不可能分配失败。就算真的分配失败,malloc会返回NULL,但你的代码没有做NULL检查——不过这不是当前问题的诱因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:05:20