Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the behavior when there are more initializers than array size?

I would like to know what happens when there are more initializers than array size, e.g. :

int t[3] = { 1, 2, 3, 4 };

Of course, my compiler warns it. I expected undefined behavior, but I didn't find any clause about it in C11 standard. So, did I miss something ?

like image 649
md5 Avatar asked Mar 07 '26 03:03

md5


2 Answers

The code is ill-formed in both C and C++.

C++11 §8.5.1[dcl.init.aggr]/6 states:

An initializer-list is ill-formed if the number of initializer-clauses exceeds the number of members or elements to initialize.

C11 §6.7.9/2 states:

No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

like image 109
James McNellis Avatar answered Mar 09 '26 16:03

James McNellis


I took a look at the assembler gcc generated for your example, and it looks like it takes the "safe" route; it simply doesn't load values past the size of the array:

void main() {
    int t[3] = { 1, 2, 3, 4 };
}

Generates the following assembly:

main:
    pushl %ebp
    movl  %esp, %ebp
    subl  $16, %esp
    movl  $1, -12(%ebp)
    movl  $2, -8(%ebp)
    movl  $3, -4(%ebp)
    leave
    ret

This was generated with gcc 4.4.3.

like image 31
Ethan Brown Avatar answered Mar 09 '26 15:03

Ethan Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!