SuperSpider
SuperSpider

Reputation: 17

C - out of index element has same address as integer

So I have this program that prints the addresses of each variable and changes the values of an integer array 'a'. When SOMETHING is 4, the values printed are as expected. However, when I change SOMETHING to 5, the value of i changes to 40, which is what would've been the value of a[4] if it existed. Why does it do this?

#define SIZE 4
#define SOMETHING 4

int index = 0;
int i;
int k = 10;
int a[SIZE] = {0, 0, 0, 0};
int j = 10;

printf("Address of the variables:\n");
printf("%lx -> &j\n", (unsigned long)&j);
for (index = 0; index < SIZE; index++) {
    printf("%lx -> &a[%d]\n", (unsigned long) &a[index], index);
}

printf("%lx -> &k\n", (unsigned long)&k);
printf("%lx -> &i\n", (unsigned long)&i);
printf("\n");


printf("Initial values: ");
printf("i = %d, j = %d, k = %d\n", i, j, k);
printf("a = {%d, %d, %d, %d}\n", a[0], a[1], a[2], a[3]);
printf("\n");


for (i = 0; i < SOMETHING; i++) {
    a[i] = i * 10;
    printf("i = %d, j = %d, k = %d\t\t", i, j, k);
    printf("a = {%d, %d, %d, %d}\n", a[0], a[1], a[2], a[3]);
}

return 0;

Upvotes: 0

Views: 57

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

Accessing an array out of bound will invoke undefined behavior. Result can be anything.

In your case, array a has 4 (SIZE) elements, so the valid index will be [0,3]. So,

  • in case, SOMETHING is 4, you have

    for (i = 0; i < 4; i++)
    

    which limits the index to 3.

  • OTOH, if you make SOMETHING as 5, you have

    for (i = 0; i < 5; i++)
    

    which actually attempts to access a[4] which is out of bound memory, creating UB.

FWIW, to print an address, use the %p format specifier and cast the argument to void*.

Upvotes: 2

Related Questions