0

I have:

#include <stdio.h>

typedef float mat4f[16];

void logMat(mat4f in) {
    int i;
    for (i=0; i<16; i++) {
        //in[i] = i; //uncomment this line and it works as expected
        printf("%2d: %f\n", i, in[i]);
    }
}

int main(void) {

    mat4f a;
    logMat(a);

    return 0;
}

When I run this, the elements at index 4 and 12 often appear corrupted. Some examples:

 0: 0.000000
 1: 0.000000
 2: 0.000000
 3: 0.000000
 4: -0.019316
 5: 0.000000
 6: 0.000000
 7: 0.000000
 8: 0.000000
 9: 0.000000
10: 0.000000
11: 0.000000
12: -0.000000
13: 0.000000
14: 0.000000
15: 0.000000

or

 0: 0.000000
 1: 0.000000
 2: 0.000000
 3: 0.000000
 4: 894113943650304.000000
 5: 0.000000
 6: 0.000000
 7: 0.000000
 8: 0.000000
 9: 0.000000
10: 0.000000
11: 0.000000
12: 0.002546
13: 0.000000
14: 0.000000
15: 0.000000

And I get different results just from running it multiple times. However, if I uncomment that one line that you'll see in the source, it works as expected every time.

Can anyone spot my mistake? Why index 4 and 12?

I'm kinda trying to do what was suggested here: stackoverflow.com/a/1810295/1472246

Community
  • 1
  • 1
Duovarious
  • 109
  • 7

2 Answers2

1

You have found a feature of C. It is often a source of tricky bugs though.

The problem is the line:

mat4f a;

It only reserves space for the variable a. It does not actually set it to any value. So a will have the value of the data that was there previously. It is often zero, but from time to time it is something else.

One way to also set a to zero is to declare it with an initializer:

mat4f a = {0};
Mats
  • 8,528
  • 1
  • 29
  • 35
1

Variables in C which are not either global or static are not guaranteed to be initialised to any particular value.

So after the line

mat4f a;

the values of the elements of a can be anything. In terms of the C language standard reading those uninitialised values invokes undefined behaviour - anything can happen.

Your commented out line explicitly sets the element values so it works as expected.

Nigel Harper
  • 1,270
  • 9
  • 13