Home >Backend Development >C++ >Does `new unsigned int` Initialize Memory to Zero in C ?

Does `new unsigned int` Initialize Memory to Zero in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 13:45:12341browse

Does `new unsigned int` Initialize Memory to Zero in C  ?

Operator new initializes memory to zero

In the following code snippet:

#include <iostream>

int main(){
  unsigned int* wsk2 = new unsigned int(5);
  std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl;
  delete wsk2;
  wsk2 = new unsigned int;
  std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl;
  return 0;
}

The expected result is that the memory is not initialized to zero, but the output is:

wsk2: 0x928e008 5
wsk2: 0x928e008 0

It seems that the operator new is initializing the memory to zero, but it is actually not.

How it works:

There are two versions of the operator new:

wsk = new unsigned int;      // default initialized (ie nothing happens)
wsk = new unsigned int();    // zero    initialized (ie set to 0)

The default initialization does not initialize the memory, while the zero initialization sets the memory to zero.

It also works for arrays:

wsa = new unsigned int[5];   // default initialized (ie nothing happens)
wsa = new unsigned int[5](); // zero    initialized (ie all elements set to 0)

To confirm that the memory is actually zeroed out, we can use placement new with a known piece of memory:

#include <new>
#include <iostream>


int main()
{
    unsigned int   wsa[5] = {1,2,3,4,5};

    // Use placement new (to use a know piece of memory).
    // In the way described above.
    // 
    unsigned int*    wsp = new (wsa) unsigned int[5]();

    std::cout << wsa[0] << "\n";   // If these are zero then it worked as described.
    std::cout << wsa[1] << "\n";   // If they contain the numbers 1 - 5 then it failed.
    std::cout << wsa[2] << "\n";
    std::cout << wsa[3] << "\n";
    std::cout << wsa[4] << "\n";
}

The output of this code is:

0
0
0
0
0

Which confirms that the memory is indeed zeroed out by the zero-initialization version of the operator new.

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

Statement:
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