Boardy Boardy - 3 years ago 174
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[] =

stringstream randomString;

//Generate a seed for the random number generator
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.


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