David Khosid
David Khosid

Reputation: 147

Problems of using srand() in libraries

There is a wide use of srand()/rand() calls in 3rd party libraries, with predefined seeds. The problem arises when combining different libraries in the same process. Sometimes it's hard to ensure the right sequence of calls, a mix of srand() and rand() calls is possible. Another problem is inability to choose seeding value on application level. As a general rule, should we avoid using srand() in libraries (including Open Source), leaving the task of seeding to applications?

Upvotes: 5

Views: 528

Answers (2)

eladidan
eladidan

Reputation: 2644

For the reasons you mentioned, among others, it's better practice in real life applications to use boost::random or C++11 random library

Upvotes: 1

Plecharts
Plecharts

Reputation: 311

If the library uses hardcoded seeds, then yes, you SHOULD have a way to change those seeds to something you declare as "random enough" to be a seed.

Also if you are using a platform that has something like /dev/urand, you probably could use that, or if you have to be multiplatform why not use something like OpenSSL's random number library? OpenSSL should probably be available on every platform you are targeting and often it is already installed, so you just need to link it.

Upvotes: 0

Related Questions