[C] Generate Random String From [a-z0-9]


Generate a random string from [a-z0-9] in C programming language.

Run code on Rextester:

ranstr.c | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* alphabet: [a-z0-9] */
const char alphabet[] = "abcdefghijklmnopqrstuvwxyz0123456789";

/**
 * not a cryptographically secure number
 * return interger [0, n).
 */
int intN(int n) { return rand() % n; }

/**
 * Input: length of the random string [a-z0-9] to be generated
 */
char *randomString(int len) {
  char *rstr = malloc((len + 1) * sizeof(char));
  int i;
  for (i = 0; i < len; i++) {
    rstr[i] = alphabet[intN(strlen(alphabet))];
  }
  rstr[len] = '\0';
  return rstr;
}

int main(int argc, char **argv) {
  // the seed for a new sequence of pseudo-random integers
  // to be returned by rand()
  srand(time(NULL));

  char *p;
  p = randomString(10);
  printf("%s\n", p);
  free(p);

  p = randomString(11);
  printf("%s\n", p);
  free(p);

  p = randomString(12);
  printf("%s\n", p);
  free(p);
}

Tested on:

  • Ubuntu 16.10
  • gcc (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005

References:

[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]