mercredi 12 janvier 2022

C rand(). Issue with generating random strings

Encountered issue with generating random strings.

Example below generates repeated blocks of random strings. Amount of random string in block depends on 'WORD_LENGTH'. For 1M 'COUNT' and 'WORD_LENGTH' of 20 chars each block contains 262144 (2^18) random strings and then block repeats.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define WORD_LENGTH 20

//const char charset[62] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const char charset[16] = "0123456789abcdef";

int main(int argc, char** argv) {
    srand(time(NULL));
    if (argc != 2) {
        printf("Usage: program COUNT'\n\n");
        return 0;
    }
    unsigned int count = atoi(argv[1]);
    char buf[WORD_LENGTH];
    for (int c = 0; c < count; c++ ) {
        for (int i = 0; i < WORD_LENGTH; ++i) {
            buf[i] = charset[ rand() % sizeof charset];
        }
        buf[WORD_LENGTH - 1] = '\0';
        printf("%s\n", buf);
    }
    return 0;
}

Important thing. I could not reproduce "issue" when "..charset[62]..." are used with 'COUNT' up to 100M. Question: Could someone please explain why it works that way ?




Aucun commentaire:

Enregistrer un commentaire