Uninitialized Class Fields and STL Containers

Does the STL provide a default zero raw memory allocator before placing objects in it? See this code. Comments reflect behavior on my platform.

#include <iostream> #include <vector> struct Foo { Foo() {} // n isn't initialized int n; }; int main() { std::vector<Foo> v(2); // zeroed std::cout << v[0].n << '\n'; std::cout << v[1].n << '\n'; Foo foo; // contains garbage std::cout << foo.n << '\n'; } 

Is it possible to disable the zeroing of raw memory? Note that this is not the same as the POD initialization value.

+4
source share
4 answers

The default container initializes the objects it creates if you do not give them a specific value. In your case, the default constructor for the object does not initialize the integer POD, so it will contain everything that remains in memory.

Sometimes new heap blocks will be zero initialized by the OS, but you can't even count on it. The unit can be reused, and again it will contain residual debris from the last use.

Code that is ultra-sensitive to exploits will take care of zeroing out memory to critical variables such as passwords before destroying them.

+2
source

It may be zero memory. Perhaps this is not so. This can bring it back from your favorite operating system that has already been reset - I know that Windows has the habit of zeroing out memory. One thing is certain - it is not defined, and you will not find any control parameters for it in the standard API.

+4
source

It looks like your free store is populated with zeros, but not your call stack. C ++, of course, does no zero initialization here, and it has nothing to do with containers.

I believe that you will see the same if you try:

 #include <iostream> #include <vector> struct Foo { Foo() {} // n isn't initialized int n; }; int main() { Foo foo; // arbitrary values std::cout << foo.n << '\n'; Foo* p = new Foo; // zero values std::cout << p->n << '\n'; delete p; } 

(Unfortunately, ideone.com does not demonstrate the behavior for an auto-storage variable, which is a shame. Something may be related to a locked environment in which g++ is called for fragments. However, I want to show my tricky use of #pragma !)


There is no C ++ way to manage this, and there is no way to manage Windows or Linux as far as I know.

By the way, everything that led you to this requirement is a good example of why you should not rely on uninitialization.

+1
source

Vector initializes its elements with copies of the object with default initialization, so in your case you get copies of an arbitrary value. Cannot disable this behavior.

0
source

All Articles