void initialization of class fields

Norbert Nemec Norbert at Nemec-online.de
Sat Aug 7 22:46:40 PDT 2010


May be a (likely) coincidence. I could imagine that any memory that is 
freshly acquired from the operating system is initialized somehow before 
it is handed over to the application. If the OS left the data written by 
some other application, this might cause security problems.

In fact, I verfied with a short C++ program that similar behavior is found:

--------------
#include <iostream>

int main() {
     int *x = new int[1024*1024];
     for(int i=0;i<50;i++)
         std::cout << x[i+200000] << "\n";
}
--------------

One call did indeed give my all zeros. For smaller chunks of memory, it 
may be more likely to get some recycled allocation that has already been 
written to by the application itself.


On 08/08/10 02:28, Andrej Mitrovic wrote:
> This is a modified example from TDPL, page 185-186, although I've increased the size of the array here:
>
> class Transmogrifier
> {
>      double[512] alpha = void;
>      size_t usedAlpha;
>
>      this()
>      {
>      }
> }
>
> void main()
> {
>      auto t = new Transmogrifier;
>      writeln(t.alpha);
> }
>
> This will write 512 zeros in my case. If I understood correctly, then alpha is an array containing 512 uninitialized values. Which is confusing me as to why I'm getting back zeros.
>
> If this was C (minus the classes), I'd get back random values at random locations in memory until I stepped into the wrong place, which would hopefully terminate my app.
>
> I guess I need a primer in how D manages memory, is what I'm really saying. :)



More information about the Digitalmars-d mailing list