Boardy Boardy - 3 years ago 164
C++ Question

Generate random string isn't always returning the correct length

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[] =
"0123456789abcdefghijklmnopqrstuvwxyz";

stringstream randomString;

//Generate a seed for the random number generator
srand(time(0));
for (int i = 0; i < length; ++i)
{
randomString << alphanum[rand() % sizeof(alphanum) - 1];
}


return randomString.str();
}


I am passing in the length of 26, and I am getting the following strings returned.

s21p7plri418swa279t0nu
u6hf
9for8meeb72hv98n9bc6wqqe3s
qoiovn


Why is it sometimes the string isn't returned in the correct length and sometimes returning more as string 3 is 27 characters instead of 26.

Answer Source

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 %.

So 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download