Home > Backend Development > C++ > Does the `new` Operator in C Always Initialize Memory to Zero?

Does the `new` Operator in C Always Initialize Memory to Zero?

Barbara Streisand
Release: 2024-12-10 22:27:26
Original
242 people have browsed it

Does the `new` Operator in C   Always Initialize Memory to Zero?

Operator new Initializes Memory to Zero

Despite the general misconception that the new operator does not initialize memory with zeroes, it can indeed accomplish this task under specific conditions.

In C , there are two main scenarios where the new operator performs zero initialization:

  1. Parentheses Initialization:

    When new is followed by parentheses and an empty initializer list, such as wsk = new unsigned int();, it explicitly invokes the default constructor of the type. For primitive types like unsigned int, the default constructor initializes the memory to zero.

  2. Parenthesized Array Initialization:

    Similar to the previous scenario, using parentheses and an empty initializer list within array declaration, like wsa = new unsigned int[5]();, initializes each element of the array to zero.

In the example code provided, the following lines showcase zero initialization:

wsk2 = new unsigned int(5);
Copy after login

This initializes wsk2 to the value 5.

wsk2 = new unsigned int;
Copy after login

This initializes wsk2 to zero because it uses the parentheses syntax without an initializer list. This behavior applies to both scalars and arrays.

In the second part of the example, the output confirms the zero initialization:

wsk2: 0x928e008 5
wsk2: 0x928e008 0
Copy after login

The first line shows that wsk2 points to the address 0x928e008 and contains the value 5. After deleting wsk2 and creating another one using new unsigned int;, the second line shows that it now points to the same address (0x928e008) but contains zero.

The above is the detailed content of Does the `new` Operator in C Always Initialize Memory to Zero?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template