Jay*_*r B 5 c matrix segmentation-fault
在我的代码中,我只是尝试使用函数 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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
#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;
}
Run Code Online (Sandbox Code Playgroud)
你正在耗尽你的筹码。由地址消毒剂提供:SUMMARY: AddressSanitizer: stack-overflow /tmp/so/m.c:42 in main.
问题是matrix太大而无法在堆栈上传递,因为您必须将 1024^2double推入堆栈(在我的系统上,这是 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);
Run Code Online (Sandbox Code Playgroud)