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

…衆ロ難τιáo~ 提交于 2019-12-10 23:29:45

问题


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 ?


回答1:


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.




回答2:


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.




回答3:


Well it depends on your compiller. Some won't even let you build with that, Visual Express gives:

error C2078: too many initializers

Where as gcc allows it to fly but warns you there are too many elements... I don't think there is a expected behavior given this case since it's undefined, but it won't work for sure.

Ex:

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

for(i = 0; i< 5; i++){
    printf("val = %d\n", t[i]);}

val = 1
val = 2
val = 3
val = 4
val = 134513760

I didn't go into disasembly, but I'm pretty sure it's just running into other data at the end.



来源:https://stackoverflow.com/questions/12182823/what-is-the-behavior-when-there-are-more-initializers-than-array-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!