Dan
Dan

Reputation: 2886

Does array declaration mean consecutive memory allocation?

int main() {
 char a[5];
 a[0] = 0;
 return a[0];
}

In this snippet, does char a[5];, which is an array declaration without any initialization, guarantee allocation of 5 bytes of consecutive memory?

Or since only 1 element gets initialized later, compiler is free to use a register for that 1 element?

I'm assuming that reading any other index of this array beside 0 is undefined behaviour.

Upvotes: 0

Views: 163

Answers (1)

0___________
0___________

Reputation: 67602

It guarantees that the observable behaviour of the program will be the same as if it has allocated this memory.

The compiler is free to optimize out any objects as in your trivial example:

main:
        xor     eax, eax
        ret

https://godbolt.org/z/KE5PzvTKq

Upvotes: 5

Related Questions