Why does printf (creating an identity matrix) not print output?

1

I cannot figure out what the problem is. The input I tried, as a command line parameter, is 3 and instead of a 3x3 identity matrix I only get this:

Process returned -1073741819 (0xC0000005) execution time : 1.545 s

Press any key to continue.

I tried several things, I read here, to fix it such as "fflush(stdout);" and "fprintf(stderr, "...") but none of them worked.

My code:

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

typedef struct matrix
{
    int N;
    double *m;
}   matrix_t;

void alloc_matrix(matrix_t* mat)
{
    mat->m = malloc(mat->N * mat->N * sizeof(double));
}

void print_matrix(matrix_t mat)
{
    printf("Test:\n" );
    for(int i = 0; i < mat.N; i++)
    {
        for(int j = 0; j < mat.N; j++)
        {
            printf("%lf ",mat.m[i * mat.N +j]);
        }
        printf("\n");
    }
}

void identity_matrix(matrix_t mat)
{
    int i, j;
    for(i = 0; i < mat.N; i++)
    {
        for (j = 0; i < mat.N; j++)
        {
            if(i == j)
            {
                mat.m[i * mat.N + j] = 1;
            } else {
                mat.m[i * mat.N + j] = 0;
            }
        }
    }
}

int main(int argc, char* argv[])
{
    int N = atoi(argv[1]);

    matrix_t inverse;
    inverse.N = N;

    alloc_matrix(&inverse);
    identity_matrix(inverse);
    print_matrix(inverse);


    return 0;
}
c
matrix
printf
output
asked on Stack Overflow Dec 1, 2018 by Levente Gáll

1 Answer

1

in identity_matrix your loop index is wrong:

   for (j = 0; i < mat.N; j++)

should be

for (j = 0; j < mat.N; j++)

so it overflows the memory and you get undefined behaviour

Note that I didn't find that by eye, your code looked okay. I first compiled it with debug & all warnings enabled

$ gcc -g -Wall test.c

No warnings, okay, so I just debugged your program, using command line:

$ gdb a
blah blah blah ....
Reading symbols from a...done.
(gdb) r 3
Starting program: L:\so\a.exe 3
[New Thread 7364.0x68c]

Program received signal SIGSEGV, Segmentation fault.
0x0000000000401686 in identity_matrix (mat=...) at test.c:40
40                      mat.m[i * mat.N + j] = 0;
(gdb) p mat
$1 = {N = 3, m = 0x3928b0}
(gdb) p i*mat.N + j
$2 = 1770
(gdb)

Either I was luckier or the memory configuration was different, but the program crashed right where the error was.

answered on Stack Overflow Dec 1, 2018 by Jean-François Fabre • edited Dec 1, 2018 by Jean-François Fabre

User contributions licensed under CC BY-SA 3.0