Strange assembly from array 0-initialization

前端 未结 3 540
清酒与你
清酒与你 2020-12-13 19:10

Inspired by the question Difference in initalizing and zeroing an array in c/c++ ?, I decided to actually examine the assembly of, in my case, an optimized release build for

3条回答
  •  伪装坚强ぢ
    2020-12-13 19:36

    Some quick testing indicates that Microsoft's x86 compiler generates different assembly if the initializer list is empty, compared to when it contains a zero. Maybe their ARM compiler does too. What happens if you do this?

    byte a[10] = { };
    

    Here's the assembly listing I got (with options /EHsc /FAs /O2 on Visual Studio 2008). Note that including a zero in the initializer list causes the compiler to use unaligned memory accesses to initialize the array, while the empty initializer list version and the memset() version both use aligned memory accesses:

    ; unsigned char a[10] = { };
    
    xor eax, eax
    mov DWORD PTR _a$[esp+40], eax
    mov DWORD PTR _a$[esp+44], eax
    mov WORD PTR _a$[esp+48], ax
    
    ; unsigned char b[10] = { 0 };
    
    mov BYTE PTR _b$[esp+40], al
    mov DWORD PTR _b$[esp+41], eax
    mov DWORD PTR _b$[esp+45], eax
    mov BYTE PTR _b$[esp+49], al
    
    ; unsigned char c[10];
    ; memset(c, 0, sizeof(c));
    
    mov DWORD PTR _c$[esp+40], eax
    mov DWORD PTR _c$[esp+44], eax
    mov WORD PTR _c$[esp+48], ax
    

提交回复
热议问题