Jim said:
John said:
This produces an initialized array to zero:
int *i = new int[100]() ;
004124B0 push ebp
004124B1 mov ebp,esp
004124B3 mov eax,dword ptr [count]
004124B6 push eax
004124B7 call operator new (411212h)
004124BC add esp,4
004124BF pop ebp
But this doesn't initialize the array. The assembly output is identical.
What's going on?
Have you looked at the assembly after this? Are you 100% sure that there
isn't some assembly after this iterating through the array and setting the
values to 0?
No, I wasn't 100% certain so I looked deeper into the disassembly code
produced from Visual Studio, and by golly, you are correct. This type (new
int[ARRAY_SIZE]()) does in fact call memset initializing the array to zero. 0
is pushed onto the stack in the call to memset.
// snippet from memset
// AL == 0 (value to be set), CX == 0xA (the size of the array)
102308CA shr ecx,2
102308CD je 102308D5
102308CF rep stos dword ptr es:[edi]
void testarray()
{
00411640 push ebp
00411641 mov ebp,esp
00411643 sub esp,10Ch
00411649 push ebx
0041164A push esi
0041164B push edi
0041164C lea edi,[ebp-10Ch]
00411652 mov ecx,43h
00411657 mov eax,0CCCCCCCCh
0041165C rep stos dword ptr es:[edi]
const int ARRAY_SIZE = 10 ;
0041165E mov dword ptr [ARRAY_SIZE],0Ah
int *i = new int[ARRAY_SIZE]() ;
00411665 mov dword ptr [ebp-104h],28h
0041166F mov eax,dword ptr [ebp-104h]
00411675 push eax
00411676 call operator new[] (4110EBh)
0041167B add esp,4
0041167E mov dword ptr [ebp-0F8h],eax
00411684 cmp dword ptr [ebp-0F8h],0
0041168B je testarray+73h (4116B3h)
0041168D mov ecx,dword ptr [ebp-104h]
00411693 push ecx
00411694 push 0
00411696 mov edx,dword ptr [ebp-0F8h]
0041169C push edx
0041169D call @ILT+155(_memset) (4110A0h) ***MEMSET HERE!***
004116A2 add esp,0Ch
004116A5 mov eax,dword ptr [ebp-0F8h]
004116AB mov dword ptr [ebp-10Ch],eax
004116B1 jmp testarray+7Dh (4116BDh)
004116B3 mov dword ptr [ebp-10Ch],0
004116BD mov ecx,dword ptr [ebp-10Ch]
004116C3 mov dword ptr
,ecx
// for ( int x = 0 ; x < ARRAY_SIZE ; x++ )
// cout << i[x] << " " ;
// cout << endl ;
int *i2 = new int[ARRAY_SIZE] ;
004116C6 push 28h
004116C8 call operator new[] (4110EBh)
004116CD add esp,4
004116D0 mov dword ptr [ebp-0ECh],eax
004116D6 mov eax,dword ptr [ebp-0ECh]
004116DC mov dword ptr [i2],eax
// for ( int x = 0 ; x < ARRAY_SIZE ; x++ )
// cout << i2[x] << " " ;
// cout << endl ;
}
004116DF pop edi
004116E0 pop esi
004116E1 pop ebx
004116E2 add esp,10Ch
004116E8 cmp ebp,esp
004116EA call @ILT+435(__RTC_CheckEsp) (4111B8h)
004116EF mov esp,ebp
004116F1 pop ebp
004116F2 ret LEAVE FUNCTION. MEMSET NOT CALLED THIS TIME.