I created this small function just to practice C code. It's a simple random string generator.
#include <string.h>
#include <time.h>
char *randstring(int length) {
static int mySeed = 25011984;
char *string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
size_t stringLen = strlen(string);
char *randomString = NULL;
srand(time(NULL) * length + ++mySeed);
if (length < 1) {
length = 1;
}
randomString = malloc(sizeof(char) * (length +1));
if (randomString) {
short key = 0;
for (int n = 0;n < length;n++) {
key = rand() % stringLen;
randomString[n] = string[key];
}
randomString[length] = '\0';
return randomString;
}
else {
printf("No memory");
exit(1);
}
}
The code seems to work ok. Any ideas, improvements or bugs?
I added the mySeed
var so that if I call it twice with the same length it doesn't give me the same exact string.
EDIT:
I have changed the code to this:
char *randstring(size_t length) {
static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
char *randomString = NULL;
if (length) {
randomString = malloc(sizeof(char) * (length +1));
if (randomString) {
for (int n = 0;n < length;n++) {
int key = rand() % (int)(sizeof(charset) -1);
randomString[n] = charset[key];
}
randomString[length] = '\0';
}
}
return randomString;
}
I know that in the sizeof(charset)
you don't have to use the ()
. You only need them when using sizeof with types, but it's just out of habit.
printf("%s\n", rand_string(buf, sizeof buf));
– William Morris Jul 30 '13 at 20:12