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?

Answers


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.


Need Your Help

html5 details tag open one by one javascript function working strange

javascript jquery html5 summary detail

I'm using the HTML5 tag details for a FAQ section of a company. An issue was that if the user opened another question the other question would not close automatically. Therefore I searched on the w...