0

I am trying to test zero initialization on virtual machine with g++ options -std=c++98, -std=c++03, -std=c++11

Unfortunately there are not so many garbage values and I see zeros in place that they shouldn't be.

How to force some random values so I can test this?

#include <iostream>
#include <string>

using namespace std;

class A
{
public:
    int a;
};


class B
{
public:
  B(){}
  int x;
};

int main()
{
    {
    int tab[50000] = {0};
    }
    A a;
    A* aa = new A;

    B b;
    B* bb = new B;

    cout << a.a << endl;
    cout << aa->a << endl;

    cout << b.x << endl;
    cout << bb->x << endl;
    return 0;
}
userbb
  • 2,148
  • 5
  • 30
  • 53
  • 2
    Sounds like a job for [placement `new`](http://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new). – LogicStuff Jan 05 '16 at 19:59
  • 1
    Allocate an array for 'garbage' values, initialize it with actual 'garbage' values and use placement new to initialize your test candidates. –  Jan 05 '16 at 20:00
  • Garbage is in the eye of the beholder. – SergeyA Jan 05 '16 at 20:06
  • 1
    A better title for this question might be "How to test/verify that zero-initialization takes place" – Joel Cornett Jan 05 '16 at 20:06
  • And it may behoove you to read through the documentation and understand when zero initialization takes place according to the standard. http://en.cppreference.com/w/cpp/language/zero_initialization – Joel Cornett Jan 05 '16 at 20:13
  • @JoelCornett yes, I know when, but I want to see this for better memorize;) – userbb Jan 05 '16 at 20:15
  • 1
    Don't really have time for a full answer, but you could `memset()` the memory associated with a variable to some non-zero value, and then use placement new to initialize it again. Note that there is not really a straightforward way to test this for the general case because initialization rules can vary based on whether the variable is stack or heap-allocated, and whether you use braced-initialization or not. You will have to look at each case and determine what the appropriate behavior is. – Joel Cornett Jan 05 '16 at 20:47
  • Well, your local array is allocated on the stack, while you are testing if the objects allocated on the heap, are zero-initialized. They won't, ever, be created in the same memory space, so your local zero-initialized array accomplishes nothing. – Algirdas Preidžius Jan 05 '16 at 20:54

1 Answers1

0

You are not guaranteed to see random numbers. The C/C++ standard just says that uninitialized values are undefined, you just cannot say which values those have. Zero is ok (maybe the virual machine zeros all memory before allocating).

If you really need random numbers, generate them using <random>

MrTux
  • 32,350
  • 30
  • 109
  • 146