Does STL default allocator zero raw memory before placing objects into it? See this code. The comments reflect the 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 zeroing raw memory? Note, it isn’t the same as value initializing POD.
A container will default-initialize the objects it creates if you don’t give them a specific value. In your case the default constructor for the object does not initialize the POD integer, so it will contain whatever was left over in memory.
Sometimes new heap blocks will be zero initialized by the OS, but you can’t even count on that. A block can get reused and again it will contain leftover garbage from the last time it was used.
Code that is ultra sensitive to exploits will take care to zero out memory to critical variables such as passwords before destroying them.