0
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.

0

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

15 Comments

Thank you. I also wanted to confirm, reading any other index here beside 0 is considered undefined behaviour correct? unless the entire array in 0 initialized in the beginning like char a[5] = {0}; ?
@Dan yes ---------
No, reading uninitialized elements of the array will produce “indeterminate” values. There is a rule in the C standard that reading uninitialized values may have undefined behavior, but it applies only to objects that could have been declared with register (and that have automatic storage duration). Array elements can never be declared with register, so the rule does not apply.
@EricPostpischil is this a C and C++ rule or only C? links with more details on this?
This link says they are undefined in C++: stackoverflow.com/questions/49696810/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.