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

调用Print_Matrix函数时触发Segmentation fault问题排查

问题:调用Print_Matrix函数打印矩阵触发段错误,main内直接打印正常

以下是复现问题的代码:

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

int N = 5;

typedef struct matrix{
    double m[1024][1024];
    int size;
}matrix;

matrix I;
void
Print_Matrix(matrix M)
{
    printf("hello\n");
    int row=0, col=0;

    for (row = 0; row < N; row++) {
        for (col = 0; col < N; col++){
            printf(" %5.2f", M.m[row][col]);
        }
        printf("\n");
    }
    printf("\n\n");
}

int main()
{
    int row, col;
    for (row = 0; row < N; row++) {
        for (col = 0; col < N; col++) {
            if (row == col)
                I.m[row][col] = 1.0;
        }
    }
    for(row=0;row<N;row++){
        for(col=0;col<N;col++){
            printf("%5.2f ", I.m[row][col]);
        }
        printf("\n");
    }
    Print_Matrix(I);


    return 0;
    
}

运行输出:

1.00  0.00  0.00  0.00  0.00 
 0.00  1.00  0.00  0.00  0.00 
 0.00  0.00  1.00  0.00  0.00 
 0.00  0.00  0.00  1.00  0.00 
 0.00  0.00  0.00  0.00  1.00 
Segmentation fault (core dumped)

问题原因

matrix结构体中的double m[1024][1024]数组大小为8MB(102410248字节)。调用Print_Matrix(I)时采用值传递,会把整个8MB的结构体拷贝到函数栈帧中,而程序默认栈空间通常只有几MB,直接撑爆栈导致段错误。

main中直接打印时访问的是全局变量I,全局变量存放在静态存储区而非栈,因此不会触发栈溢出。

解决方案

将函数参数改为指针传递,仅传递一个4/8字节的指针,避免大量栈空间占用:

修改后的Print_Matrix函数:

void Print_Matrix(const matrix *M)
{
    printf("hello\n");
    int row=0, col=0;

    for (row = 0; row < N; row++) {
        for (col = 0; col < N; col++){
            printf(" %5.2f", M->m[row][col]);
        }
        printf("\n");
    }
    printf("\n\n");
}

main函数中的调用改为:

Print_Matrix(&I);

这样即可正常打印矩阵,不会出现段错误。

内容的提问来源于stack exchange,提问作者Jaya Shankar B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:30:49