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

数组出现Segmentation fault:通过用户输入行列数创建数组时运行崩溃

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

核心问题

  • 数组定义时机错误:代码中int arr[rows];和int arr1[column];在rows、column未初始化时就定义了变长数组。此时这两个变量的值是内存中的随机垃圾值,导致数组大小不可控,后续读写数组元素必然触发内存越界,引发段错误。

修复方案

方案1:调整数组定义顺序(使用变长数组)

先获取用户输入的行列数,再基于合法值定义数组:

#include<stdio.h>
int main(){
    int rows;
    int column;
    
    // 先获取合法的行列值
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    printf("Enter the number of column: ");
    scanf("%d",&column);
    printf("\n");
    
    // 基于已初始化的变量定义数组
    int arr[rows];
    int arr1[column];
    
    int i=0;
    while( i<rows)
    {  
        printf("\nEnter the value of rows index: ");
        scanf("%d",&arr[i]);
        printf("\n");
        i++;
    }
    int j=0;
    while(j<column)
    {
        printf("Enter the value of column index: "); // 修正原代码的提示文本错误
        scanf("%d",&arr1[j]);
        printf("\n");
        j++;
    }
    return 0;
}

方案2:动态内存分配(更灵活通用)

使用malloc动态申请内存,适配更多场景且不受变长数组编译器支持限制:

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

int main(){
    int rows;
    int column;
    int *arr;
    int *arr1;
    
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    printf("Enter the number of column: ");
    scanf("%d",&column);
    printf("\n");
    
    // 动态分配内存并检查是否成功
    arr = (int*)malloc(rows * sizeof(int));
    arr1 = (int*)malloc(column * sizeof(int));
    if(arr == NULL || arr1 == NULL){
        printf("Memory allocation failed!\n");
        return 1;
    }
    
    int i=0;
    while( i<rows)
    {  
        printf("\nEnter the value of rows index: ");
        scanf("%d",&arr[i]);
        printf("\n");
        i++;
    }
    int j=0;
    while(j<column)
    {
        printf("Enter the value of column index: ");
        scanf("%d",&arr1[j]);
        printf("\n");
        j++;
    }
    
    // 释放动态内存,避免泄漏
    free(arr);
    free(arr1);
    
    return 0;
}

额外注意事项

  • 变长数组(VLA)是C99标准特性,部分编译器(如MSVC)需开启特定支持才能使用
  • 动态内存分配后必须调用free释放内存,防止内存泄漏
  • 建议增加输入校验,确保用户输入的行列数为正整数,避免数组大小非法导致的异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:05:33