Cobra_Fast
Cobra_Fast

Reputation: 16061

Why does my random string generator produce too short strings?

I have written a simple function that returns a random string.

std::string cache::generateCacheName()
{
    static const char pool[] = "0123456789abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string r;
    std::random_device rd;
    std::mt19937 eng(rd());
    std::uniform_int_distribution<> distr(0, sizeof(pool) - 1);
    for (int i = 0; i < 48; i++)
        r += pool[distr(eng)];
    return r;
}

However, sometimes it returns a string randomly shorter than 48 characters.

I already added the - 1 behind the sizeof(pool) trying to avoid adding the null-terminator from pool, but that didn't change anything.

Where did I go wrong?

Upvotes: 2

Views: 136

Answers (1)

Chris Uzdavinis
Chris Uzdavinis

Reputation: 6131

a) given a string literal "123", the size is 4, because it's an array of 4 const characters, counting the null.

b) When you subtract 1 from that size, you get 3.

c) When you have an array of 3 elements, the 3rd element is at offset 2.

d) std::uniform_int_distribution is defined over the closed interval [a,b]. That is, up to and including both endpoints form a to b.

e) When you pick a random number and it happens to be the largest value in that interval (in this case, 3) you grab the trailing null byte from pool and insert it into your string. You probably want a max value of 2, not 3.

Therefore, your string is short if it happens to select the largest number in your distribution. Perhaps your code would be clearer with strlen(pool)-1, as long as it isn't empty.

Upvotes: 6

Related Questions