For example:
int main()
{
int p;
::std::cout << ::std::uintptr_t(&p) << ::std::endl;
}
This will consistently produce "random" numbers if executed repeatedly. Something similar could be accomplished in C. I don't see anything UB about it.
For example:
int main()
{
int p;
::std::cout << ::std::uintptr_t(&p) << ::std::endl;
}
This will consistently produce "random" numbers if executed repeatedly. Something similar could be accomplished in C. I don't see anything UB about it.
I quite depends on requirements you set on the distribution of the random numbers. Is the sequence 1,1,1,1,1,1,1,1 random ? Actually hard to tell, but if you make a test for a normal distribution it will certainly fail. Pseudo random number generators are specifically designed to match the properties of the random distribution you want to get from them.
If you do some trickery to get a previously unknown number (on purpose I dont call it random), this number might appear random to you, but it is very likely that there are patterns that you just dont spot.
TL;DR: it is not easy to write a good rng. Use the ones that are available if you need random numbers.
No, no, no.
You cannot use variable addresses, values of uninitialized variables and the like as sources of random numbers.
Some of those uses will earn you a ticket straight to "undefined behaviour land" where your compiler is allowed to do horrible, horrible things to your code.
Some are just not really all that random.
If you want random numbers, use what's provided in < random > and make sure you seed your generator properly if you are not using random_device
directly (which you probably don't want to for non-crypto-safe numbers).
And don't even consider rand()
- forget it exists. It is horrible.
You should use a std::seed_seq
to mix up multiple entropy sources and then use that to seed the generator. Taking the address of a variable as one of many inputs for seed_seq
would be ok, assuming you also include other sources of higher quality (notably std::random_device
).
If your OS randomizes the stack address of your program, you can extract several random bits from the address of your local variable. These will probably be high-quality random bits (if your OS is good), but there will be only a few, because:
So this method is not good because its result relies heavily on OS (as an extreme example, a user can disable ASLR, and your random number generator will stop working for that user).
int
are much fewer and, on top of that, the algorithm by which your program gets loaded into memory, if not documented, it at least is not built for much randomness.In any case, this is all assuming you use the address of the variable (perfectly valid) and not its value (undefined behavior if uninitialized). If you invoke undefined behavior, the operation could throw away all your entropy.