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

C语言动态分配二维数组行数大于列数时出现段错误

问题分析与修复

核心错误:指针数组内存分配大小不匹配

你的代码中创建二维数组的第一步存在关键内存分配错误:

int **matrix = (int **)calloc(*rows, sizeof(int));

这里你为指针数组分配的是sizeof(int)的空间,但int**类型的数组每个元素是指针(int*)。在64位系统中,指针大小为8字节,而int通常是4字节,这导致分配的内存空间仅为实际需求的一半。

当行数≤列数时,可能只是暂时没触发非法内存访问的边界;但行数>列数时,指针数组的内存越界会被快速触发,直接引发段错误。

次要错误:main函数的语法问题

main里的变量声明存在语法冗余:

int rows, int cols; // 错误:重复使用int关键字

应修正为:

int rows, cols;

修复后的完整代码

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

int **create_input_matrix(int *rows, int *cols) {
    printf("Number of lines: ");
    scanf("%d", rows);
    printf("Number of cols: ");
    scanf("%d", cols);
    // 修正:为指针数组分配int*大小的空间
    int **matrix = (int **)calloc(*rows, sizeof(int*));
    for (int i = 0; i < *rows; i++) {
        matrix[i] = (int *)calloc(*cols, sizeof(int));
    }
    printf("Matrix elements:\n");
    for (int i = 0; i < *rows; i++) {
        for (int j = 0; j < *cols; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
    return matrix;
}

int main() {
   int rows, cols; // 修正语法错误
   int **mat = create_input_matrix(&rows, &cols);
   // 额外:使用完后释放内存,避免泄漏
   for (int i = 0; i < rows; i++) {
       free(mat[i]);
   }
   free(mat);
   return 0;
}

额外提示

  • 动态分配的内存使用完毕后必须释放,否则会造成内存泄漏。
  • 可以添加calloc返回值的合法性检查,避免内存分配失败时的未知行为:
if (matrix == NULL) {
    perror("Failed to allocate memory for rows");
    exit(EXIT_FAILURE);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:20:32