5

In my code, I am just trying to print initialized matrix using the function Print_Matrix(M), but when the function I am getting a segmentation fault, but when I print it within the main function it prints as expected

Here is my code to replicate the issue

#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;
    
}

Output:

 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)
Jaya Shankar B
  • 121
  • 2
  • 8
  • Please [edit] your question to show us a [mre]. What is, for example, `N`? What is it's relation to `MAX_SIZE`? And what is `MAX_SIZE`? – Some programmer dude Oct 15 '22 at 12:05
  • And have you tried to use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to catch the crash to see exactly when and where in your code it actually happens? – Some programmer dude Oct 15 '22 at 12:06
  • 1
    Hi @Someprogrammerdude I tried the debugger tool but I can't get go into the function to see in which line its failing – Jaya Shankar B Oct 15 '22 at 12:29

1 Answers1

5

You're blowing your stack. Courtesy of address sanitizer: SUMMARY: AddressSanitizer: stack-overflow /tmp/so/m.c:42 in main.

The issue is that matrix is too big to pass on the stack, since you have 1024^2 doubles that have to get pushed onto the stack (on my system, this is 8388608 bytes). When dealing with large objects, pass them via pointer to other functions.

Relevant changes:

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);
Stephen Newell
  • 7,330
  • 1
  • 24
  • 28