Jaya Shankar B
Jaya Shankar B

Reputation: 133

Getting Segementation fault while calling a function

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)

Upvotes: 5

Views: 53

Answers (1)

Stephen Newell
Stephen Newell

Reputation: 7863

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

Upvotes: 5

Related Questions