1

I have this following code where is generated only a fixed string everytime that the program is executed, already tested in 2 computers and always is generated the same string. Then how generate a diferent string in each execution?

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;
}

// int _tmain(int argc, _TCHAR* argv[])

char str[MAX_PATH]; 
gen_random(str, 10);
  • Either use a true RNG or cheat somehow like taking the hash of a timestamp (not guaranteed to be unique without unique salts) – MeetTitan Jan 28 '19 at 15:34
  • 1
    Did you seed the random number generator in `main()`? Something like `std::srand(std::time(0));`? – Galik Jan 28 '19 at 15:35
  • Alternative methods suggested here: https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c – Galik Jan 28 '19 at 15:39
  • @Galik, thank you. `std::srand(std::time(0));` solved the question. –  Jan 28 '19 at 15:46

2 Answers2

2

rand generally is a Pseudo-Random Number Generator. The number sequence is fully determined by the PRNG's seed, as set with srand. Since you don't set the seed explicitly, you always get the same seed and thus the same sequence.

Please note that the newer <random> header has better solutions - better algorithms, better seeding, more range, additional distributions, ...

MSalters
  • 173,980
  • 10
  • 155
  • 350
2

The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

Same seed, same string every time. You need to srand() using a random seed. If it isn't security relevant then the time is usually a good seed. Otherwise you need to get true random bits from the operating system. Under Linux / Unix you would read /dev/random for that.

Community
  • 1
  • 1
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42