Brett
Brett

Reputation: 12007

C/C++ - generating a random string overwrites previous (see code below)

I am trying to generate a random alphanumeric string using the code found here (function code repeated below):

Code:

void gen_random(char *s, const int len) {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
    }

    s[len] = 0;
}

At first glance, this works great. However when I call the function twice, the returning value gets overwritten. Let me explain. When I use the code:

char image_id[32];
gen_random(image_id, 32); //image_id is correctly populated with a random string at this point.

char feature_id[32];
gen_random(feature_id, 32); //feature_id is correctly populated with a random string at this point. However, image_id is now an empty string?!?!?

image_id becomes an empty string. However, if I remove the last line gen_random(feature_id, 32); (or breakpoint before it), then image_id is correctly stored.

How can this be possible? What am I missing here?

Upvotes: 0

Views: 190

Answers (1)

Yu Hao
Yu Hao

Reputation: 122403

I'm not sure if this is the root reason to cause your problem, but it's an error: inside the function gen_random:

s[len] = 0;

When you are calling gen_random(image_id, 32);, you are assigning image_32[32] which causes buffer overflow as the array image_32 has only 32 elements. Only index 0 to 31would be valid.

Upvotes: 3

Related Questions