Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a dynamic allocation of characters using new require for the compiler to initialize them to zero

Tags:

c++

c++11

For example:

char *p=new char[100];

Must the character array pointed to by p be initialized to zeroes per the C++ standard? Or, is this behavior completely compiler dependant?

gcc seems to call the default constructor on each character, which of course initializes them to zero. Visual C++ 2010 does not.

like image 722
Michael Goldshteyn Avatar asked Dec 29 '25 20:12

Michael Goldshteyn


1 Answers

No, POD types are left uninitialised when they are created by new. You could value-initialise them to zero if you want:

char * p = new char[100]();
                        ^^

This is specified by the standard:

C++11, 5.3.4/15: If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value.

8.5/6: To default-initialize an object of type T means:
— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is an array type, each element is default-initialized;
— otherwise, no initialization is performed.

Your other observation:

gcc seems to call the default constructor on each character

It shouldn't do - especially as char doesn't have a constructor. If you replace it with a type with a default constructor, then that will be called for each element.

I get the following disassembly, with no sign of any initialisation:

int main() {
    char * p = new char[100];
    return p[0];
}

00000000004005f4 <main>:
  # set up stack frame
  push   %rbp
  mov    %rsp,%rbp
  sub    $0x10,%rsp

  # call `operator new[]` with an argument of 100
  mov    $0x64,%edi
  callq  4004e0 <operator new[](unsigned long)@plt>

  # put the return value into %eax
  mov    %rax,-0x8(%rbp)
  mov    -0x8(%rbp),%rax
  movzbl (%rax),%eax
  movsbl %al,%eax

  # return
  leaveq 
  retq   
like image 192
Mike Seymour Avatar answered Jan 01 '26 10:01

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!