C++ Bus error when using `^=` and `<<` on a class member `unsigned long`
-
17-03-2021 - |
Question
I am trying to implement the random number generator defined in this answer. There is some ambiguity, at least from my knowledge, as to how the first line, static unsigned long x=123456789, y=362436069, z=521288629;
should be implemented, since it is shown outside the function. I assumed that it was intended as a class member and implemented it thus:
class rng2{
public:
unsigned long x, y, z;
rng2() : x(123456789), y(362436069), z(521288629) {}
unsigned long xorshf96(void) { //period 2^96-1
//static unsigned long x=123456789, y=362436069, z=521288629;
unsigned long t;
x ^= x << 16; //BUS ERROR, debug mode
x ^= x >> 5;
x ^= x << 1;
t = x;
x = y; //SEG FAULT, release mode
y = z;
z = t ^ x ^ y;
return z;
}
};
int main ()
{
rng2 rand2;
rng2 * prand;
for(long d =0; d < 10000; d++)
cout << "\n" << (*prand).xorshf96();
}
For some reason, this gives me errors at the noted locations, depending on which mode I compile with. However, if I comment out the member variable and the constructor and use the static variable instead, everything works. If this is the correct code, I don't see why it was shown differently at the link, and either way, I don't know why the error is happening.
La solution
You're using *prand, but not initializing prand.
Autres conseils
rng2 * prand;
Are you perfectly sure this is the real code? Considering you are not initializing this pointer and dereferencing it later, the error is pretty obvious.
prand
is a wild pointer.
Change:
int main ()
{
rng2 rand2;
rng2 * prand;
for(long d =0; d < 10000; d++)
cout << "\n" << (*prand).xorshf96();
}
to:
int main ()
{
rng2 rand2;
rng2 * prand = &rand2;
for(long d =0; d < 10000; d++)
cout << "\n" << (*prand).xorshf96();
}
or better just:
int main ()
{
rng2 rand2;
for(long d =0; d < 10000; d++)
cout << "\n" << rand2.xorshf96();
}
This is because the prand
pointer is never assigned but only used. When using a static
the variable no datamember is accessed and that's why you do not get a bus error. You should definately assign your pointer a valid value in your main function. Like this
rng2 * prand = new rng2();