From owner-freebsd-questions Sun Mar 23 22:24:56 2003 Delivered-To: freebsd-questions@freebsd.org Received: from mx1.FreeBSD.org (mx1.freebsd.org [216.136.204.125]) by hub.freebsd.org (Postfix) with ESMTP id 99B3737B401 for ; Sun, 23 Mar 2003 22:24:54 -0800 (PST) Received: from mail.gmx.net (imap.gmx.net [213.165.65.60]) by mx1.FreeBSD.org (Postfix) with SMTP id 4736B43F85 for ; Sun, 23 Mar 2003 22:24:53 -0800 (PST) (envelope-from blueeskimo@gmx.net) Received: (qmail 14350 invoked by uid 0); 24 Mar 2003 06:24:49 -0000 Received: from i216-58-29-174.gta.igs.net (HELO ?216.58.29.174?) (216.58.29.174) by mail.gmx.net (mp008-rz3) with SMTP; 24 Mar 2003 06:24:49 -0000 Subject: Re: Generating passwords From: Adam To: Jan-Espen Pettersen Cc: tony@idk.com, questions@freebsd.org In-Reply-To: <20030324050457.8F4841276DA@login.kvalito.no> References: <20030324050457.8F4841276DA@login.kvalito.no> Content-Type: text/plain Organization: Message-Id: <1048487087.15312.85.camel@jake> Mime-Version: 1.0 X-Mailer: Ximian Evolution 1.2.2 Date: 24 Mar 2003 01:24:47 -0500 Content-Transfer-Encoding: 7bit Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk List-ID: List-Archive: (Web Archive) List-Help: (List Instructions) List-Subscribe: List-Unsubscribe: X-Loop: FreeBSD.ORG 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 To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message