I'm making a simple program that generates a random password of some length with or without special characters, just for the sake of learning the C language. Finally I've got this working very well based on the outputs below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char *generate_random_password(int password_lenght, int has_special_characters)
{
const char *letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char *digits = "0123456789";
const char *special_characters = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
char *random_password = malloc(sizeof(char) * (password_lenght+1));
srandom(time(NULL));
if(has_special_characters)
{
char to_be_used[95] = "\0";
strcat(to_be_used, letters);
strcat(to_be_used, digits);
strcat(to_be_used, special_characters);
for(int i = 0; i < password_lenght; i++)
{
const int random_index = random() % strlen(to_be_used);
const char random_character = to_be_used[random_index];
random_password[i] = random_character;
}
}
else
{
char to_be_used[63] = "\0";
strcat(to_be_used, letters);
strcat(to_be_used, digits);
for(int i = 0; i < password_lenght; i++)
{
const int random_index = random() % strlen(to_be_used);
const char random_character = to_be_used[random_index];
random_password[i] = random_character;
}
}
return random_password;
free(random_password);
}
int main(void)
{
printf("%s\n", generate_random_password(17, 1));
printf("%s\n", generate_random_password(17, 0));
return 0;
}
The output is:
|ZzN>^5}8:i-P8197
vPrbfzBEGzmSdaPPP
It's working!
But I'm completely in doubt about these strings, pointers, char arrays, etc. I have no idea if this is written "the right way" or how it could be better. I'm concerned if I allocated the right amount for each string/char array, and if it can break or crash in some future.
PS: I'm new at C programming, that's why I don't know much about pointers and memory management yet.
If can anyone give me some feedback about it I will be very grateful!
srandom
andrandom
. If this is intended, please edit your post to include your target and host programming platform, as reviewers can add platform dependent notes. You might also add relevant tags. If you intended to create platform independent code, feel free to also edit your post to indicate this. \$\endgroup\$to_be_used
is now initialized before the firststrcat
reads it. I would have usedstrcpy
instead of zeroing that local on the stack and then using strcat. Or really I would have done what @Baldrickk suggests and not done any copying). But anyway, this is a repost with some of the bugs fixed. I guess still a crosspost but I was wondering why nobody was mentioning the things from the SO comments) \$\endgroup\$