[Solved] Alphanumeric String Generation in C [closed]


As pointed out by #IngoLeonhardt, use % (sizeof(alphanum) - 1) instead of % sizeof(alphanum)

My guess is that you don’t have room for your string, try:

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

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 main(void)
{
    char *str = malloc(8 + 1);

    /* initialize random seed: */
    srand(time(NULL));  
    gen_random(str, 8);
    printf("%s\n", str);
    free(str);
    return 0;
}

6

solved Alphanumeric String Generation in C [closed]