Salma - 10 months ago 41

C Question

I have a global struct that has an array as part of it as follows:

*First Implementation:*

When I print any value of the array with index higher that

`490`

`#define NUMOFROWS 512`

struct matrix {

int freeSpace;

int allocSapce;

unsigned long long bit_matrix[NUMOFROWS];

};

int main() {

struct matrix b;

b.bitmap_matrix[NUMOFROWS] = 0;

printf("MA[0] = %llu \n", b.bitmap_matrix[0]);

printf("MA[5] = %llu \n", b.bitmap_matrix[5]);

printf("MA[511] = %llu \n", b.bitmap_matrix[511]);

return 0;

}

OUTPUT:

`MA[0] = 0`

MA[5] = 0

MA[511] = 140734799804304

I changed it into this, then it worked fine.

`#define ROWS 512`

struct matrix {

int freeSpace;

int allocSapce;

unsigned long long bit_matrix[NUMOFROWS];

};

int main() {

struct matrix b;

for (int i = 0 ; i < ROWS; i++) {

b.bit_matrix[i] = 0;

}

printf("MA[0] = %llu \n", b.bit_matrix[0]);

printf("MA[5] = %llu \n", b.bit_matrix[5]);

printf("MA[511] = %llu \n", b.bit_matrix[511]);

return 0;

}

OUTPUT:

`MA[0] = 0`

MA[5] = 0

MA[511] = 0

Any idea why?

Answer Source

The structure `b`

is not global, it has automatic storage (aka *on the stack*). The type declaration for `struct matrix`

is global but the instance `b`

is local to the `main`

function.

As such it is uninitialized, any members you do not explicitly initialize is uninitialized, even just reading the values invokes undefined behavior.

Furthermore, you access an element of the array beyond the size of the array: `b.bitmap_matrix[NUMOFROWS] = 0;`

invokes undefined behavior too.

Here is a simpler version using an initializer:

```
#define ROWS 512
struct matrix {
int freeSpace;
int allocSapce;
unsigned long long bit_matrix[NUMOFROWS];
};
int main(void) {
struct matrix b = { 0 };
printf("MA[0] = %llu\n", b.bitmap_matrix[0]);
printf("MA[5] = %llu\n", b.bitmap_matrix[5]);
printf("MA[511] = %llu\n", b.bitmap_matrix[511]);
return 0;
}
```

Output:

```
MA[0] = 0
MA[5] = 0
MA[511] = 0
```