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

向动态数组添加元素时出现Segmentation Fault的问题求助

问题原因分析
  • 核心致命错误:代码中if (teleportPlaces != NULL) { teleportPlaces = NULL; }的逻辑完全错误,内存申请成功后主动将指针置空,后续循环对teleportPlaces[i]赋值属于空指针解引用,这是触发段错误的根本原因。
  • 其他不规范问题:
    1. calloc参数写死了数值2,没有复用已定义的长度变量,后续调整数组大小时容易出现参数不匹配问题
    2. 长度变量名lenght为拼写错误,标准拼写为length,不影响运行但不利于代码维护
    3. 缺失必要头文件,使用calloc、printf、free需要引入<stdio.h>和<stdlib.h>,部分编译器下缺失头文件会触发未定义行为
修复后的可运行代码
#include <stdio.h>
#include <stdlib.h>

typedef struct teleporter {
    int start;
    int end;
} teleporters;

int main(int argc, char **argv) {
    int length = 2;
    teleporters *teleportPlaces;
    teleporters mytele;
    mytele.start = 0;
    mytele.end = 0;
    // 复用长度变量作为申请元素个数的参数
    teleportPlaces = calloc(length, sizeof(teleporters));
    // 正确判空逻辑:内存申请失败直接退出,不操作空指针
    if (teleportPlaces == NULL) {
        printf("内存申请失败\n");
        return -1;
    }
    for (int i = 0; i < length; i++) {
        teleportPlaces[i] = mytele;
    }

    printf("Teleport END[0] = %d", teleportPlaces[0].end);
    free(teleportPlaces);
    return 0;
}
扩展注意事项
  • 后续需要给动态数组扩容时,使用realloc调整已申请的内存大小,不要直接重复调用malloc,否则会丢失原有数据、产生内存泄漏
  • 所有堆内存申请操作都必须做判空处理,避免申请失败后的空指针操作
  • 不再使用的堆内存要及时调用free释放,避免内存泄漏,释放后可以主动将指针置为NULL,避免野指针访问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:24:03