Strange values while initializing array using designated initializers

前端 未结 5 1069
迷失自我
迷失自我 2021-02-07 05:57

When I initialize the array below all the output looks ok except for values[3]. For some reason values[3] initialized as values[0]+values[5]

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-07 06:34

    This is the first time that I have seen something initialized that way, but I figured that the behavior you are seeing had to do with accessing a piece of the array that has not yet been initialized. So I built it using GCC 4.6.3 on a 32-bit Ubuntu 12.04 system. In my environment, I got different results than you.

    gcc file.c -o file
    
    ./file
    values[0] = 197
    values[1] = 0
    values[2] = -100
    values[3] = 197
    values[4] = 0
    values[5] = 350
    values[6] = 0
    values[7] = 0
    values[8] = 0
    values[9] = 35
    
    
    objdump -d file > file.asm
    
    cat file.asm     (relevant portion posted below)
    
    080483e4 
    : 80483e4: 55 push %ebp 80483e5: 89 e5 mov %esp,%ebp 80483e7: 57 push %edi 80483e8: 53 push %ebx 80483e9: 83 e4 f0 and $0xfffffff0,%esp 80483ec: 83 ec 40 sub $0x40,%esp 80483ef: 8d 5c 24 14 lea 0x14(%esp),%ebx 80483f3: b8 00 00 00 00 mov $0x0,%eax 80483f8: ba 0a 00 00 00 mov $0xa,%edx 80483fd: 89 df mov %ebx,%edi 80483ff: 89 d1 mov %edx,%ecx 8048401: f3 ab rep stos %eax,%es:(%edi) <===== 8048403: c7 44 24 14 c5 00 00 movl $0xc5,0x14(%esp) 804840a: 00 804840b: c7 44 24 1c 9c ff ff movl $0xffffff9c,0x1c(%esp) 8048412: ff 8048413: 8b 54 24 14 mov 0x14(%esp),%edx 8048417: 8b 44 24 28 mov 0x28(%esp),%eax 804841b: 01 d0 add %edx,%eax 804841d: 89 44 24 20 mov %eax,0x20(%esp) 8048421: c7 44 24 28 5e 01 00 movl $0x15e,0x28(%esp) 8048428: 00 8048429: 8b 4c 24 28 mov 0x28(%esp),%ecx 804842d: ba 67 66 66 66 mov $0x66666667,%edx 8048432: 89 c8 mov %ecx,%eax 8048434: f7 ea imul %edx 8048436: c1 fa 02 sar $0x2,%edx 8048439: 89 c8 mov %ecx,%eax 804843b: c1 f8 1f sar $0x1f,%eax

    I've identified a key line in the above output that I think marks the difference between what yours generated and what mine generated (marked with <======). Before specific array elements are initialized with the values you specified, mine is zeroing the contents of the array. The specific initialization of array elements occurs after this.

    Given the above behavior, I do not think that it is unreasonable to hypothesize that yours did not zero the array contents prior to initializing specific elements of the array. As to why the difference in behavior? I can only speculate; but my first guess is that we are using two different compiler versions.

    Hope this helps.

提交回复
热议问题