Salma - 1 year ago 64
C Question

# Garbage Value When initialized all element of a global array

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`
, it prints garbage value.

``````#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
``````

Second Implementation:

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?

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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download