I am working on a project I am trying to generate a random string. Its mostly working, except for some reason, every now and again the string returned isn't the correct length.
Below is my code:
string HelperMethods::generateRandomString(int length)
static const char alphanum =
//Generate a seed for the random number generator
for (int i = 0; i < length; ++i)
randomString << alphanum[rand() % sizeof(alphanum) - 1];
There's a NUL character in
alphanum. After all, it's a C-string. And while you try to exclude it,
- has lower precedence than
rand() % sizeof(alphanum) - 1 is the same as
(rand() % sizeof(alphanum)) - 1. You are likely accessing before the first element of the array some of the time. That's just plain undefined behavior right there.
Furthermore, you aren't supposed to seed the random number generator more than once. That's likely skewing the results as well. But it isn't as much of an issue as the undefined behavior, of course.