在调用函数时出现分段错误

5

在我的代码中,我只是尝试使用函数Print_Matrix(M)打印初始化的矩阵,但当调用该函数时,我遇到了一个段错误,但当我在主函数内打印它时,它按预期打印出来。

这是复制问题的代码:

#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)

请编辑您的问题以展示一个最小可重现示例(MRE)。例如,N是什么?它与MAX_SIZE有什么关系?而MAX_SIZE又是什么? - Some programmer dude
你尝试过使用调试器来捕获崩溃并查看它在代码中确切发生的时间和位置吗? - Some programmer dude
1
嗨 @Someprogrammerdude,我尝试了调试工具,但是我无法进入函数以查看它在哪一行失败。 - Jaya Shankar B
1个回答

5

你的栈溢出了。感谢地址消毒剂:SUMMARY: AddressSanitizer: stack-overflow /tmp/so/m.c:42 in main

问题在于matrix太大,在堆栈上传递它太费资源,因为你有1024^2个double要被压入堆栈中(在我的系统上,这是8388608字节)。当处理大型对象时,请通过指针将它们传递给其他函数。

相关更改:

void
Print_Matrix(matrix const *M) // using a pointer
{
    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]); // using -> instead of .
        }
        printf("\n");
    }
    printf("\n\n");
}
// ...

// later, in main
    Print_Matrix(&I);

1
考虑使用 const* 作为承诺不更改给定矩阵的方式:void Print_Matrix(matrix const* M)。在C++中,我甚至更喜欢使用 const& - user5329483
@user5329483 - 这是一个非常好的建议,我感到有些尴尬自己没有想到。 - Stephen Newell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接