My first random password generatorRandom Sentences generatorRandom quote generatorSimple random number generatorEfficient random code generatorPassword generator scriptSimple random password generatorPassword generator in DjangoRandom exam generatorPython 3.4 password generatorPython password generator

Why would they pick a gamma distribution here?

Can a Creature at 0 HP Take Damage?

How slow was the 6502 BASIC compared to Assembly

I pay for a service, but I miss the broadcast

What if a quote contains an error

In 1700s, why was 'books that never read' grammatical?

one-liner vs script

Why does allocating a single 2D array take longer than a loop allocating multiple 1D arrays of the same total size and shape?

How to make "acts of patience" exciting?

Low-magic medieval fantasy clothes that allow the wearer to grow?

Why has Donald Trump's popularity remained so stable over a rather long period of time?

How stable are PID loops really?

Scalar `new T` vs array `new T[1]`

Difference between $HOME and ~

I am confused with the word order when putting a sentence into passé composé with reflexive verbs

Was Wayne Brady considered a guest star on the original "Whose Line Is It Anyway?"

If LPG gas burners can reach temperatures above 1700 °C, then how do HCA and PAH not develop in extreme amounts during cooking?

Is sleeping on the groud in cold weather better than on an air mattress?

Why didn't Snape ask Dumbledore why he let "Moody" search his office?

Can something have more sugar per 100g than the percentage of sugar that's in it?

How to make a gift without seeming creepy?

Describing the taste of food

How long could a human survive completely without the immune system?

Is there a more efficient alternative to pull down resistors?



My first random password generator


Random Sentences generatorRandom quote generatorSimple random number generatorEfficient random code generatorPassword generator scriptSimple random password generatorPassword generator in DjangoRandom exam generatorPython 3.4 password generatorPython password generator






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









6












$begingroup$


I'm making a simple program that generate some random password of some lenght 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] = "";

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] = "";

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("%sn", generate_random_password(17, 1));
printf("%sn", 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 this strings, pointers, char arrays, etc. I have no idea if this is written "the right way" or how it should 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!










share|improve this question









New contributor



maverick1013 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$









  • 1




    $begingroup$
    Cross-posted to Stack Overflow
    $endgroup$
    – Mast
    8 hours ago










  • $begingroup$
    @Mast But.. why? This is on-topic for CR.
    $endgroup$
    – Reinderien
    7 hours ago










  • $begingroup$
    @Reinderien I know, it was posted there first. It being on-topic here and off-topic there doesn't make it less of a cross-post.
    $endgroup$
    – Mast
    7 hours ago






  • 1




    $begingroup$
    Please don't misunderstand, @Reinderien. Mast did not post it to Stack Overflow, but only mentioned that there is already a post on SO. That way, interested reviewers can have a look at the comments on SO and include them in their own review. It's not, however, a comment that indicates that this question might be on-topic on SO. It's only a note on the post's previous history, which happened to be on SO.
    $endgroup$
    – Zeta
    7 hours ago






  • 2




    $begingroup$
    Welcome to CodeReview, maverick. Your code is currently not platform independent due to the use of srandom and random. 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$
    – Zeta
    7 hours ago

















6












$begingroup$


I'm making a simple program that generate some random password of some lenght 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] = "";

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] = "";

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("%sn", generate_random_password(17, 1));
printf("%sn", 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 this strings, pointers, char arrays, etc. I have no idea if this is written "the right way" or how it should 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!










share|improve this question









New contributor



maverick1013 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$









  • 1




    $begingroup$
    Cross-posted to Stack Overflow
    $endgroup$
    – Mast
    8 hours ago










  • $begingroup$
    @Mast But.. why? This is on-topic for CR.
    $endgroup$
    – Reinderien
    7 hours ago










  • $begingroup$
    @Reinderien I know, it was posted there first. It being on-topic here and off-topic there doesn't make it less of a cross-post.
    $endgroup$
    – Mast
    7 hours ago






  • 1




    $begingroup$
    Please don't misunderstand, @Reinderien. Mast did not post it to Stack Overflow, but only mentioned that there is already a post on SO. That way, interested reviewers can have a look at the comments on SO and include them in their own review. It's not, however, a comment that indicates that this question might be on-topic on SO. It's only a note on the post's previous history, which happened to be on SO.
    $endgroup$
    – Zeta
    7 hours ago






  • 2




    $begingroup$
    Welcome to CodeReview, maverick. Your code is currently not platform independent due to the use of srandom and random. 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$
    – Zeta
    7 hours ago













6












6








6





$begingroup$


I'm making a simple program that generate some random password of some lenght 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] = "";

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] = "";

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("%sn", generate_random_password(17, 1));
printf("%sn", 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 this strings, pointers, char arrays, etc. I have no idea if this is written "the right way" or how it should 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!










share|improve this question









New contributor



maverick1013 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$




I'm making a simple program that generate some random password of some lenght 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] = "";

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] = "";

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("%sn", generate_random_password(17, 1));
printf("%sn", 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 this strings, pointers, char arrays, etc. I have no idea if this is written "the right way" or how it should 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!







beginner c






share|improve this question









New contributor



maverick1013 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



maverick1013 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited 2 hours ago









Reinderien

10.5k19 silver badges46 bronze badges




10.5k19 silver badges46 bronze badges






New contributor



maverick1013 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 8 hours ago









maverick1013maverick1013

333 bronze badges




333 bronze badges




New contributor



maverick1013 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




maverick1013 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • 1




    $begingroup$
    Cross-posted to Stack Overflow
    $endgroup$
    – Mast
    8 hours ago










  • $begingroup$
    @Mast But.. why? This is on-topic for CR.
    $endgroup$
    – Reinderien
    7 hours ago










  • $begingroup$
    @Reinderien I know, it was posted there first. It being on-topic here and off-topic there doesn't make it less of a cross-post.
    $endgroup$
    – Mast
    7 hours ago






  • 1




    $begingroup$
    Please don't misunderstand, @Reinderien. Mast did not post it to Stack Overflow, but only mentioned that there is already a post on SO. That way, interested reviewers can have a look at the comments on SO and include them in their own review. It's not, however, a comment that indicates that this question might be on-topic on SO. It's only a note on the post's previous history, which happened to be on SO.
    $endgroup$
    – Zeta
    7 hours ago






  • 2




    $begingroup$
    Welcome to CodeReview, maverick. Your code is currently not platform independent due to the use of srandom and random. 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$
    – Zeta
    7 hours ago












  • 1




    $begingroup$
    Cross-posted to Stack Overflow
    $endgroup$
    – Mast
    8 hours ago










  • $begingroup$
    @Mast But.. why? This is on-topic for CR.
    $endgroup$
    – Reinderien
    7 hours ago










  • $begingroup$
    @Reinderien I know, it was posted there first. It being on-topic here and off-topic there doesn't make it less of a cross-post.
    $endgroup$
    – Mast
    7 hours ago






  • 1




    $begingroup$
    Please don't misunderstand, @Reinderien. Mast did not post it to Stack Overflow, but only mentioned that there is already a post on SO. That way, interested reviewers can have a look at the comments on SO and include them in their own review. It's not, however, a comment that indicates that this question might be on-topic on SO. It's only a note on the post's previous history, which happened to be on SO.
    $endgroup$
    – Zeta
    7 hours ago






  • 2




    $begingroup$
    Welcome to CodeReview, maverick. Your code is currently not platform independent due to the use of srandom and random. 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$
    – Zeta
    7 hours ago







1




1




$begingroup$
Cross-posted to Stack Overflow
$endgroup$
– Mast
8 hours ago




$begingroup$
Cross-posted to Stack Overflow
$endgroup$
– Mast
8 hours ago












$begingroup$
@Mast But.. why? This is on-topic for CR.
$endgroup$
– Reinderien
7 hours ago




$begingroup$
@Mast But.. why? This is on-topic for CR.
$endgroup$
– Reinderien
7 hours ago












$begingroup$
@Reinderien I know, it was posted there first. It being on-topic here and off-topic there doesn't make it less of a cross-post.
$endgroup$
– Mast
7 hours ago




$begingroup$
@Reinderien I know, it was posted there first. It being on-topic here and off-topic there doesn't make it less of a cross-post.
$endgroup$
– Mast
7 hours ago




1




1




$begingroup$
Please don't misunderstand, @Reinderien. Mast did not post it to Stack Overflow, but only mentioned that there is already a post on SO. That way, interested reviewers can have a look at the comments on SO and include them in their own review. It's not, however, a comment that indicates that this question might be on-topic on SO. It's only a note on the post's previous history, which happened to be on SO.
$endgroup$
– Zeta
7 hours ago




$begingroup$
Please don't misunderstand, @Reinderien. Mast did not post it to Stack Overflow, but only mentioned that there is already a post on SO. That way, interested reviewers can have a look at the comments on SO and include them in their own review. It's not, however, a comment that indicates that this question might be on-topic on SO. It's only a note on the post's previous history, which happened to be on SO.
$endgroup$
– Zeta
7 hours ago




2




2




$begingroup$
Welcome to CodeReview, maverick. Your code is currently not platform independent due to the use of srandom and random. 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$
– Zeta
7 hours ago




$begingroup$
Welcome to CodeReview, maverick. Your code is currently not platform independent due to the use of srandom and random. 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$
– Zeta
7 hours ago










2 Answers
2






active

oldest

votes


















4














$begingroup$

Typo



lenght is spelled length.



Magic numbers



What does 95 signify? You'll want to put this in a named #define or a const.



Allocation failure



After calling malloc, always check that you've been given a non-null pointer. Allocation failure does happen in real life.



Indentation



You'll want to run this through an autoformatter, because your if block has wonky indentation and needs more columns to the right.



Inaccessible statement




return random_password;

free(random_password);


This free will never be called; delete it.



Random



The larger conceptual problem with this program is that it uses a very cryptographically weak pseudorandom number generator. This is a large and fairly complex topic, so you'll need to do some reading, but asking for random data from an entropy-controlled system source will already be better than using C rand.



That aside: you aren't calling rand, you're calling random:




The random() function uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to RAND_MAX. The period of this random number generator is very large, approximately 16 * ((2^31) - 1).




It's probably not appropriate for cryptographic purposes. Have a read through this:



https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c/39475626#39475626






share|improve this answer











$endgroup$














  • $begingroup$
    Thank you for the accept, but I suggest that you instead unaccept, upvote, and wait a while for other suggestions to come in for other users before you decide on an accepted answer.
    $endgroup$
    – Reinderien
    7 hours ago










  • $begingroup$
    Thanks, I will write the Allocation Failure test for the malloc(). About the free(), I read that after using malloc() to manual allocate some memory, I also need to manualy free the memory after using it. I put free() after the return because when I put it before, the string "random_password" was returned empty, I don't know why, maybe the free() before "deleted" the variable in some way. The random() function is Linux only.
    $endgroup$
    – maverick1013
    7 hours ago











  • $begingroup$
    return terminates the function, so nothing after it will be run. But you're correct to identify that, in general, allocated memory should be freed. In this case, it would be the responsibility of main to do that.
    $endgroup$
    – Reinderien
    7 hours ago










  • $begingroup$
    Agreed that the C library rand function is cryptographically weak, but this isn't cryptography. Even knowing the exact random algorithm used it wouldn't help you crack the password, particularly as you don't know any of it. Taking the remainder of the generated number mod the length of the character set would further obfusticate things. Knowing nothing more, you would still have to run through all RAND_MAX possibilities.
    $endgroup$
    – Peter Jennings
    4 hours ago











  • $begingroup$
    @PeterJennings Key and password generation are absolutely activities requiring cryptographic strength. Given that password generation requires a tiny amount of data and only needs to occur once, the marginal added cost and complexity are more than worth it - even if it brings password attacks from "infeasible" to "extremely infeasible".
    $endgroup$
    – Reinderien
    2 hours ago


















1














$begingroup$

Whilst your code works, there are a number of simplifications that you might try.



1) As Reinderien says, get rid of "magic" numbers



2) Having done that, declare a single string containing all 95 characters with the special ones last. This does away with all the strcat code.



3) It's good practice to declare has_special_characters as type bool. Depending on the flavour of C you are using, you may have to include stdbool.h.



4) You can then test it to set an integer variable, modulus_divider, to the correct const or #define value as in 1)



5) You can then take the modulus of the random number with modulus_divider That way you don't need to keep using strlen(to_be_used)and you only need one generating loop.



6) You don't really need all the intermediate variables in your for loop. Assuming you have set up char_set as you full 94 character array as in 2), your entire for loop could become



for(int i = 0; i < password_lenght; i++)

random_password[i] = char_set[random() % modulus_divider];






share|improve this answer








New contributor



Peter Jennings is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





$endgroup$
















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );







    maverick1013 is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f229927%2fmy-first-random-password-generator%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    $begingroup$

    Typo



    lenght is spelled length.



    Magic numbers



    What does 95 signify? You'll want to put this in a named #define or a const.



    Allocation failure



    After calling malloc, always check that you've been given a non-null pointer. Allocation failure does happen in real life.



    Indentation



    You'll want to run this through an autoformatter, because your if block has wonky indentation and needs more columns to the right.



    Inaccessible statement




    return random_password;

    free(random_password);


    This free will never be called; delete it.



    Random



    The larger conceptual problem with this program is that it uses a very cryptographically weak pseudorandom number generator. This is a large and fairly complex topic, so you'll need to do some reading, but asking for random data from an entropy-controlled system source will already be better than using C rand.



    That aside: you aren't calling rand, you're calling random:




    The random() function uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to RAND_MAX. The period of this random number generator is very large, approximately 16 * ((2^31) - 1).




    It's probably not appropriate for cryptographic purposes. Have a read through this:



    https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c/39475626#39475626






    share|improve this answer











    $endgroup$














    • $begingroup$
      Thank you for the accept, but I suggest that you instead unaccept, upvote, and wait a while for other suggestions to come in for other users before you decide on an accepted answer.
      $endgroup$
      – Reinderien
      7 hours ago










    • $begingroup$
      Thanks, I will write the Allocation Failure test for the malloc(). About the free(), I read that after using malloc() to manual allocate some memory, I also need to manualy free the memory after using it. I put free() after the return because when I put it before, the string "random_password" was returned empty, I don't know why, maybe the free() before "deleted" the variable in some way. The random() function is Linux only.
      $endgroup$
      – maverick1013
      7 hours ago











    • $begingroup$
      return terminates the function, so nothing after it will be run. But you're correct to identify that, in general, allocated memory should be freed. In this case, it would be the responsibility of main to do that.
      $endgroup$
      – Reinderien
      7 hours ago










    • $begingroup$
      Agreed that the C library rand function is cryptographically weak, but this isn't cryptography. Even knowing the exact random algorithm used it wouldn't help you crack the password, particularly as you don't know any of it. Taking the remainder of the generated number mod the length of the character set would further obfusticate things. Knowing nothing more, you would still have to run through all RAND_MAX possibilities.
      $endgroup$
      – Peter Jennings
      4 hours ago











    • $begingroup$
      @PeterJennings Key and password generation are absolutely activities requiring cryptographic strength. Given that password generation requires a tiny amount of data and only needs to occur once, the marginal added cost and complexity are more than worth it - even if it brings password attacks from "infeasible" to "extremely infeasible".
      $endgroup$
      – Reinderien
      2 hours ago















    4














    $begingroup$

    Typo



    lenght is spelled length.



    Magic numbers



    What does 95 signify? You'll want to put this in a named #define or a const.



    Allocation failure



    After calling malloc, always check that you've been given a non-null pointer. Allocation failure does happen in real life.



    Indentation



    You'll want to run this through an autoformatter, because your if block has wonky indentation and needs more columns to the right.



    Inaccessible statement




    return random_password;

    free(random_password);


    This free will never be called; delete it.



    Random



    The larger conceptual problem with this program is that it uses a very cryptographically weak pseudorandom number generator. This is a large and fairly complex topic, so you'll need to do some reading, but asking for random data from an entropy-controlled system source will already be better than using C rand.



    That aside: you aren't calling rand, you're calling random:




    The random() function uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to RAND_MAX. The period of this random number generator is very large, approximately 16 * ((2^31) - 1).




    It's probably not appropriate for cryptographic purposes. Have a read through this:



    https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c/39475626#39475626






    share|improve this answer











    $endgroup$














    • $begingroup$
      Thank you for the accept, but I suggest that you instead unaccept, upvote, and wait a while for other suggestions to come in for other users before you decide on an accepted answer.
      $endgroup$
      – Reinderien
      7 hours ago










    • $begingroup$
      Thanks, I will write the Allocation Failure test for the malloc(). About the free(), I read that after using malloc() to manual allocate some memory, I also need to manualy free the memory after using it. I put free() after the return because when I put it before, the string "random_password" was returned empty, I don't know why, maybe the free() before "deleted" the variable in some way. The random() function is Linux only.
      $endgroup$
      – maverick1013
      7 hours ago











    • $begingroup$
      return terminates the function, so nothing after it will be run. But you're correct to identify that, in general, allocated memory should be freed. In this case, it would be the responsibility of main to do that.
      $endgroup$
      – Reinderien
      7 hours ago










    • $begingroup$
      Agreed that the C library rand function is cryptographically weak, but this isn't cryptography. Even knowing the exact random algorithm used it wouldn't help you crack the password, particularly as you don't know any of it. Taking the remainder of the generated number mod the length of the character set would further obfusticate things. Knowing nothing more, you would still have to run through all RAND_MAX possibilities.
      $endgroup$
      – Peter Jennings
      4 hours ago











    • $begingroup$
      @PeterJennings Key and password generation are absolutely activities requiring cryptographic strength. Given that password generation requires a tiny amount of data and only needs to occur once, the marginal added cost and complexity are more than worth it - even if it brings password attacks from "infeasible" to "extremely infeasible".
      $endgroup$
      – Reinderien
      2 hours ago













    4














    4










    4







    $begingroup$

    Typo



    lenght is spelled length.



    Magic numbers



    What does 95 signify? You'll want to put this in a named #define or a const.



    Allocation failure



    After calling malloc, always check that you've been given a non-null pointer. Allocation failure does happen in real life.



    Indentation



    You'll want to run this through an autoformatter, because your if block has wonky indentation and needs more columns to the right.



    Inaccessible statement




    return random_password;

    free(random_password);


    This free will never be called; delete it.



    Random



    The larger conceptual problem with this program is that it uses a very cryptographically weak pseudorandom number generator. This is a large and fairly complex topic, so you'll need to do some reading, but asking for random data from an entropy-controlled system source will already be better than using C rand.



    That aside: you aren't calling rand, you're calling random:




    The random() function uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to RAND_MAX. The period of this random number generator is very large, approximately 16 * ((2^31) - 1).




    It's probably not appropriate for cryptographic purposes. Have a read through this:



    https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c/39475626#39475626






    share|improve this answer











    $endgroup$



    Typo



    lenght is spelled length.



    Magic numbers



    What does 95 signify? You'll want to put this in a named #define or a const.



    Allocation failure



    After calling malloc, always check that you've been given a non-null pointer. Allocation failure does happen in real life.



    Indentation



    You'll want to run this through an autoformatter, because your if block has wonky indentation and needs more columns to the right.



    Inaccessible statement




    return random_password;

    free(random_password);


    This free will never be called; delete it.



    Random



    The larger conceptual problem with this program is that it uses a very cryptographically weak pseudorandom number generator. This is a large and fairly complex topic, so you'll need to do some reading, but asking for random data from an entropy-controlled system source will already be better than using C rand.



    That aside: you aren't calling rand, you're calling random:




    The random() function uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to RAND_MAX. The period of this random number generator is very large, approximately 16 * ((2^31) - 1).




    It's probably not appropriate for cryptographic purposes. Have a read through this:



    https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c/39475626#39475626







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 7 hours ago

























    answered 7 hours ago









    ReinderienReinderien

    10.5k19 silver badges46 bronze badges




    10.5k19 silver badges46 bronze badges














    • $begingroup$
      Thank you for the accept, but I suggest that you instead unaccept, upvote, and wait a while for other suggestions to come in for other users before you decide on an accepted answer.
      $endgroup$
      – Reinderien
      7 hours ago










    • $begingroup$
      Thanks, I will write the Allocation Failure test for the malloc(). About the free(), I read that after using malloc() to manual allocate some memory, I also need to manualy free the memory after using it. I put free() after the return because when I put it before, the string "random_password" was returned empty, I don't know why, maybe the free() before "deleted" the variable in some way. The random() function is Linux only.
      $endgroup$
      – maverick1013
      7 hours ago











    • $begingroup$
      return terminates the function, so nothing after it will be run. But you're correct to identify that, in general, allocated memory should be freed. In this case, it would be the responsibility of main to do that.
      $endgroup$
      – Reinderien
      7 hours ago










    • $begingroup$
      Agreed that the C library rand function is cryptographically weak, but this isn't cryptography. Even knowing the exact random algorithm used it wouldn't help you crack the password, particularly as you don't know any of it. Taking the remainder of the generated number mod the length of the character set would further obfusticate things. Knowing nothing more, you would still have to run through all RAND_MAX possibilities.
      $endgroup$
      – Peter Jennings
      4 hours ago











    • $begingroup$
      @PeterJennings Key and password generation are absolutely activities requiring cryptographic strength. Given that password generation requires a tiny amount of data and only needs to occur once, the marginal added cost and complexity are more than worth it - even if it brings password attacks from "infeasible" to "extremely infeasible".
      $endgroup$
      – Reinderien
      2 hours ago
















    • $begingroup$
      Thank you for the accept, but I suggest that you instead unaccept, upvote, and wait a while for other suggestions to come in for other users before you decide on an accepted answer.
      $endgroup$
      – Reinderien
      7 hours ago










    • $begingroup$
      Thanks, I will write the Allocation Failure test for the malloc(). About the free(), I read that after using malloc() to manual allocate some memory, I also need to manualy free the memory after using it. I put free() after the return because when I put it before, the string "random_password" was returned empty, I don't know why, maybe the free() before "deleted" the variable in some way. The random() function is Linux only.
      $endgroup$
      – maverick1013
      7 hours ago











    • $begingroup$
      return terminates the function, so nothing after it will be run. But you're correct to identify that, in general, allocated memory should be freed. In this case, it would be the responsibility of main to do that.
      $endgroup$
      – Reinderien
      7 hours ago










    • $begingroup$
      Agreed that the C library rand function is cryptographically weak, but this isn't cryptography. Even knowing the exact random algorithm used it wouldn't help you crack the password, particularly as you don't know any of it. Taking the remainder of the generated number mod the length of the character set would further obfusticate things. Knowing nothing more, you would still have to run through all RAND_MAX possibilities.
      $endgroup$
      – Peter Jennings
      4 hours ago











    • $begingroup$
      @PeterJennings Key and password generation are absolutely activities requiring cryptographic strength. Given that password generation requires a tiny amount of data and only needs to occur once, the marginal added cost and complexity are more than worth it - even if it brings password attacks from "infeasible" to "extremely infeasible".
      $endgroup$
      – Reinderien
      2 hours ago















    $begingroup$
    Thank you for the accept, but I suggest that you instead unaccept, upvote, and wait a while for other suggestions to come in for other users before you decide on an accepted answer.
    $endgroup$
    – Reinderien
    7 hours ago




    $begingroup$
    Thank you for the accept, but I suggest that you instead unaccept, upvote, and wait a while for other suggestions to come in for other users before you decide on an accepted answer.
    $endgroup$
    – Reinderien
    7 hours ago












    $begingroup$
    Thanks, I will write the Allocation Failure test for the malloc(). About the free(), I read that after using malloc() to manual allocate some memory, I also need to manualy free the memory after using it. I put free() after the return because when I put it before, the string "random_password" was returned empty, I don't know why, maybe the free() before "deleted" the variable in some way. The random() function is Linux only.
    $endgroup$
    – maverick1013
    7 hours ago





    $begingroup$
    Thanks, I will write the Allocation Failure test for the malloc(). About the free(), I read that after using malloc() to manual allocate some memory, I also need to manualy free the memory after using it. I put free() after the return because when I put it before, the string "random_password" was returned empty, I don't know why, maybe the free() before "deleted" the variable in some way. The random() function is Linux only.
    $endgroup$
    – maverick1013
    7 hours ago













    $begingroup$
    return terminates the function, so nothing after it will be run. But you're correct to identify that, in general, allocated memory should be freed. In this case, it would be the responsibility of main to do that.
    $endgroup$
    – Reinderien
    7 hours ago




    $begingroup$
    return terminates the function, so nothing after it will be run. But you're correct to identify that, in general, allocated memory should be freed. In this case, it would be the responsibility of main to do that.
    $endgroup$
    – Reinderien
    7 hours ago












    $begingroup$
    Agreed that the C library rand function is cryptographically weak, but this isn't cryptography. Even knowing the exact random algorithm used it wouldn't help you crack the password, particularly as you don't know any of it. Taking the remainder of the generated number mod the length of the character set would further obfusticate things. Knowing nothing more, you would still have to run through all RAND_MAX possibilities.
    $endgroup$
    – Peter Jennings
    4 hours ago





    $begingroup$
    Agreed that the C library rand function is cryptographically weak, but this isn't cryptography. Even knowing the exact random algorithm used it wouldn't help you crack the password, particularly as you don't know any of it. Taking the remainder of the generated number mod the length of the character set would further obfusticate things. Knowing nothing more, you would still have to run through all RAND_MAX possibilities.
    $endgroup$
    – Peter Jennings
    4 hours ago













    $begingroup$
    @PeterJennings Key and password generation are absolutely activities requiring cryptographic strength. Given that password generation requires a tiny amount of data and only needs to occur once, the marginal added cost and complexity are more than worth it - even if it brings password attacks from "infeasible" to "extremely infeasible".
    $endgroup$
    – Reinderien
    2 hours ago




    $begingroup$
    @PeterJennings Key and password generation are absolutely activities requiring cryptographic strength. Given that password generation requires a tiny amount of data and only needs to occur once, the marginal added cost and complexity are more than worth it - even if it brings password attacks from "infeasible" to "extremely infeasible".
    $endgroup$
    – Reinderien
    2 hours ago













    1














    $begingroup$

    Whilst your code works, there are a number of simplifications that you might try.



    1) As Reinderien says, get rid of "magic" numbers



    2) Having done that, declare a single string containing all 95 characters with the special ones last. This does away with all the strcat code.



    3) It's good practice to declare has_special_characters as type bool. Depending on the flavour of C you are using, you may have to include stdbool.h.



    4) You can then test it to set an integer variable, modulus_divider, to the correct const or #define value as in 1)



    5) You can then take the modulus of the random number with modulus_divider That way you don't need to keep using strlen(to_be_used)and you only need one generating loop.



    6) You don't really need all the intermediate variables in your for loop. Assuming you have set up char_set as you full 94 character array as in 2), your entire for loop could become



    for(int i = 0; i < password_lenght; i++)

    random_password[i] = char_set[random() % modulus_divider];






    share|improve this answer








    New contributor



    Peter Jennings is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





    $endgroup$



















      1














      $begingroup$

      Whilst your code works, there are a number of simplifications that you might try.



      1) As Reinderien says, get rid of "magic" numbers



      2) Having done that, declare a single string containing all 95 characters with the special ones last. This does away with all the strcat code.



      3) It's good practice to declare has_special_characters as type bool. Depending on the flavour of C you are using, you may have to include stdbool.h.



      4) You can then test it to set an integer variable, modulus_divider, to the correct const or #define value as in 1)



      5) You can then take the modulus of the random number with modulus_divider That way you don't need to keep using strlen(to_be_used)and you only need one generating loop.



      6) You don't really need all the intermediate variables in your for loop. Assuming you have set up char_set as you full 94 character array as in 2), your entire for loop could become



      for(int i = 0; i < password_lenght; i++)

      random_password[i] = char_set[random() % modulus_divider];






      share|improve this answer








      New contributor



      Peter Jennings is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      $endgroup$

















        1














        1










        1







        $begingroup$

        Whilst your code works, there are a number of simplifications that you might try.



        1) As Reinderien says, get rid of "magic" numbers



        2) Having done that, declare a single string containing all 95 characters with the special ones last. This does away with all the strcat code.



        3) It's good practice to declare has_special_characters as type bool. Depending on the flavour of C you are using, you may have to include stdbool.h.



        4) You can then test it to set an integer variable, modulus_divider, to the correct const or #define value as in 1)



        5) You can then take the modulus of the random number with modulus_divider That way you don't need to keep using strlen(to_be_used)and you only need one generating loop.



        6) You don't really need all the intermediate variables in your for loop. Assuming you have set up char_set as you full 94 character array as in 2), your entire for loop could become



        for(int i = 0; i < password_lenght; i++)

        random_password[i] = char_set[random() % modulus_divider];






        share|improve this answer








        New contributor



        Peter Jennings is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        $endgroup$



        Whilst your code works, there are a number of simplifications that you might try.



        1) As Reinderien says, get rid of "magic" numbers



        2) Having done that, declare a single string containing all 95 characters with the special ones last. This does away with all the strcat code.



        3) It's good practice to declare has_special_characters as type bool. Depending on the flavour of C you are using, you may have to include stdbool.h.



        4) You can then test it to set an integer variable, modulus_divider, to the correct const or #define value as in 1)



        5) You can then take the modulus of the random number with modulus_divider That way you don't need to keep using strlen(to_be_used)and you only need one generating loop.



        6) You don't really need all the intermediate variables in your for loop. Assuming you have set up char_set as you full 94 character array as in 2), your entire for loop could become



        for(int i = 0; i < password_lenght; i++)

        random_password[i] = char_set[random() % modulus_divider];







        share|improve this answer








        New contributor



        Peter Jennings is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.








        share|improve this answer



        share|improve this answer






        New contributor



        Peter Jennings is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.








        answered 3 hours ago









        Peter JenningsPeter Jennings

        1114 bronze badges




        1114 bronze badges




        New contributor



        Peter Jennings is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.




        New contributor




        Peter Jennings is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.


























            maverick1013 is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded

















            maverick1013 is a new contributor. Be nice, and check out our Code of Conduct.












            maverick1013 is a new contributor. Be nice, and check out our Code of Conduct.











            maverick1013 is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f229927%2fmy-first-random-password-generator%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

            Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

            Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її