Skip site navigation (1)Skip section navigation (2)
Date:      24 Mar 2003 01:24:47 -0500
From:      Adam <blueeskimo@gmx.net>
To:        Jan-Espen Pettersen <sigsegv@login.kvalito.no>
Cc:        tony@idk.com, questions@freebsd.org
Subject:   Re: Generating passwords
Message-ID:  <1048487087.15312.85.camel@jake>
In-Reply-To: <20030324050457.8F4841276DA@login.kvalito.no>
References:  <20030324050457.8F4841276DA@login.kvalito.no>

next in thread | previous in thread | raw e-mail | index | archive | help
On Mon, 2003-03-24 at 00:04, Jan-Espen Pettersen wrote:
> This C program will generate random passwords.
> ...
> int main()
> {
>  int min_lenght = 8;
>  int max_lenght = 30;
>  int a;
>  long int b;
>  char *c = "-abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ---_/*+1234567890!#---1234567890-";
>  char *d; 
>  long int e;
>  srandomdev();
>  e = random();
>  e = min_lenght + (e % ((max_lenght - min_lenght) + 1));
>  printf("lenght=%d\n", e);
>  e++;
>  d = (char *) malloc(e);
>  e--;
>  d[e] = 0;
>  a = 0;
>  while (a < e)
>  {
>   b = random();
>   b = b % strlen(c);
>   d[a] = c[b];
>   a++;
>  };
>  printf("password=\"%s\"\n", d);
> };

I have a few issues with this code .. 
a) You never free() your malloc'ed memory

b) You shouldn't call strlen(c) every time you iterate through the
while() loop (since 'c' isn't changing). Set this length in a variable
before the while loop, then make use of that variable. This could even
be a #define, since the string is hard-coded.

c) I'm not sure this is completely portable: d[e] = 0;
Just in case, I'd suggest: d[e] = '\0';

d) Combine these two lines:
b = random();
b = b % strlen(c);
--> b = random() % len; // using 'len' variable as I mentioned before. 

e) You never return from main(). Some compilers will be very unhappy
about this. Better to be explicit.

f) You don't check the return value of malloc(). This should be a
no-brainer. *Always* check the return value of malloc/calloc, no matter
how little memory you are requesting.

-- 
Adam <blueeskimo@gmx.net>


To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?1048487087.15312.85.camel>