Operator New Initializes Memory to Zero

Operator new initializes memory to zero

There are two versions:

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

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)

In answer to comment below.

Ehm... are you sure that new unsigned int[5]() zeroes the integers?

Apparently yes:

[C++11: 5.3.4/15]: A new-expression that creates an object of type T initializes that object as follows: If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value. Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.

#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";
}

Results:

> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.2.0
Thread model: posix
> g++ t.cpp
> ./a.out
0
0
0
0
0
>

How to initialise memory with new operator in C++?

It's a surprisingly little-known feature of C++ (as evidenced by the fact that no-one has given this as an answer yet), but it actually has special syntax for value-initializing an array:

new int[10]();

Note that you must use the empty parentheses — you cannot, for example, use (0) or anything else (which is why this is only useful for value initialization).

This is explicitly permitted by ISO C++03 5.3.4[expr.new]/15, which says:

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

...

  • If the new-initializer is of the form (), the item is value-initialized (8.5);

and does not restrict the types for which this is allowed, whereas the (expression-list) form is explicitly restricted by further rules in the same section such that it does not allow array types.

What does it mean to initialize memory to zero in C?

p = calloc(12, 1024);

Is roughly equivalent to:

p = malloc(12 * 1024);
if (p != NULL)
memset(p, 0, 12 * 1024);

So calloc does two things that malloc does not:

  • It multiplies the nmemb and size variables to calculate the total size of the allocation
  • It sets every byte of the allocation to zero

For this purpose, calloc is good for allocating arrays, particular arrays of scalar values.

There are cases where this initialization is undesirable:

  • Initialization to all-zero bits is insufficient for pointers, where NULL may not be all zeros.
  • If you're going to use the allocation as a buffer and will be reading data into it, then it's a waste of time to initialize it to all-zeros first.

What does the JVM do when 'new' operator initializes the memory using the constructor?

new operator doesn't actually uses the help from constructor to allocate memory. It has nothing to do with constructor. Basically Java's version of malloc is new.

new operator:

  • allocates memory for an object
  • invokes object constructor
  • returns reference to that memory

Constructor is executed separately to perform any operations during initialization, like allocating values to objects and variables. If no Constructor is defined, then compiler will create default constructor and will allocate default values:


The following chart summarizes the default values for several data types.
source

Data Type   Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String null
any object null
boolean false

So, new operator only allocates memory and returns reference to that memory.

See the documentation:

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

force g++ to zero initialize memory

Thanks for your answers, but I'd like a less invasive technique, as the classes are part of the test, and their constructor is right in the midle of the subject which is dependency injection.

I was just hopping for something similar to visual studio which sets the memory to some specific value in debug mode (I think?), through an option of g++ or something alike.

some answers/comments basically fall back to saying "don't test it, just don't make the mistake"

Finally, I've overloaded the new operator and added a call to memset(ptr, 0, size);
and I get my critical check p->m_pB != __null failed, it works fine.

you all get a +1 anyway, especially DeadMg for the interesting solution

operator new doesn't return 0 when running out of memory

I've found my error: I called new wrong: new NoMemory();
The correct way to do is new NoMemory; (without the parentheses)

Now it works like a charm, like this:

#include <iostream>
#include <cstdlib>
#include <new> // bad_alloc definition
using namespace std;

int count = 0;

class NoMemory {
int array[100000];
public:

void* operator new(size_t sz) throw(bad_alloc)
{
void* p = ::new(std::nothrow) char[sz];
if(0 != p)
return p;
throw bad_alloc();
}
};


int main() {
try {
while(1) {
count++;
new NoMemory;
}
}
catch(bad_alloc)
{
cout << "memory exhausted after " << count << " allocations!" << endl;
cout << "Out of memory exception" << endl;
exit(1);
}
}


Related Topics



Leave a reply



Submit