MSVC2013 and array newline initialization issue

I was looking at this little snippet:

#include <iostream>
#include <cstring>

int main()
{
    char const *a = "my string";
    size_t len = strlen(a);
    char *b = new char[len + 1]{0};

    char *zeroes = new char[strlen(a) + 1];
    memset(zeroes, 0, strlen(a) + 1);

    std::cout << memcmp(b, zeroes, strlen(a) + 1); // 0 expected
}

      

gcc and clang output correctly 0

but MSVC2013 Update 3 outputs 1

.

I read 5.3.4/17

about new

and new-initializer, but couldn't find anything to justify the MSVC behavior.

Am I missing something? Is this a known issue?


Edit: I am attaching a memory dump from MSVC and generated assembly code (x64 release)

enter image description here

int main()
{
000007F676571270  push        rbx  
000007F676571272  sub         rsp,20h  
    char const *a = "my string";
    size_t len = strlen(a);
    char *b = new char[len + 1]{0};
000007F676571276  mov         ecx,0Ah  
000007F67657127B  call        operator new[] (07F676571704h)  
000007F676571280  mov         rbx,rax  
000007F676571283  test        rax,rax  
000007F676571286  je          main+1Dh (07F67657128Dh)  
000007F676571288  mov         byte ptr [rax],0  // zero the first one out
000007F67657128B  jmp         main+1Fh (07F67657128Fh)  
000007F67657128D  xor         ebx,ebx  

    char *zeroes = new char[strlen(a) + 1];
000007F67657128F  mov         ecx,0Ah  
000007F676571294  call        operator new[] (07F676571704h)  

      

+3


source to share


1 answer


This is a MS VC ++ compiler error. According to C ++ standard (5.3.4 New)

17 A new expression that creates an object of type T initializes this object as follows:

- If new initializer is omitted, the object is initialized by default (8.5); if initialization fails, the object is undefined.

- Otherwise, new-initializer is interpreted according to 8.5 initialization rules for directinitialization.

And further (8.5.1 Aggregates)

7 If the list has fewer initializer clauses than the aggregate, then each member not explicitly initialized shall be initialized from its own equalized or equalinitializer element, or, if there are no parentheses-or-equalinitializer, from an empty initializer list (8.5. 4).

and (8.5.4 List Initialization)



- Otherwise, if there are no elements in the initializer list, the object is value-initialized

and finally (8.5 Initializers)

8 To initialize an object of type, type T means

...

- if T is an array type, then each element is initialized with a value; - otherwise, the object is initialized to zero.

So, all the elements of the array must be zero-initialized.

+2


source







All Articles