Veeno
Veeno

Reputation: 113

Which *_cast should I use to cast an arbitrary integer-type pointer to a char pointer?

I need to fill an integer-type variable (of arbitrary size) with data from /dev/urandom. With that in mind, I have the following piece of code:

std::fstream fstr("/dev/urandom", std::fstream::in | std::fstream::binary);
fstr.read(reinterpret_cast<char*>(&randomseed), sizeof(randomseed));
fstr.close();

(randomseed is the variable which I need to fill with random data).

Will this do the right thing (i.e. is it safe regardless of library implementation), or should I use some other *_cast?

Upvotes: 2

Views: 101

Answers (1)

MSalters
MSalters

Reputation: 180235

It's NOT safe. Only the char types are guaranteed to have no trap representations.

The "proper" solution is to wrap /dev/urandom in a C++ <random> engine, and use a std::uniform_int_distribution.

Upvotes: 1

Related Questions