[vox-tech] RE: vox-tech digest, Vol 1 #104 - 14 msgs

Ken Bloom vox-tech@lists.lugod.org
Fri, 1 Feb 2002 08:49:10 -0800


> -----Original Message-----
> Date: Thu, 31 Jan 2002 23:25:47 -0800 (PST)
> From: Jeff Newmiller <jdnewmil@dcn.davis.ca.us>
> To: vox-tech@lists.lugod.org
> Subject: Re: [vox-tech] [C newbie]C program is acting weird...
> Reply-To: vox-tech@lists.lugod.org
>
> On Thu, 31 Jan 2002, Ryan wrote:
>
> > -----BEGIN PGP SIGNED MESSAGE-----
> > Hash: SHA1
> >
> > for some reason this is spitting out 3 char responses once in a
> while, anyone
> > have any ideas? I don't know much C, this is just some code I modified.
> >
> > Also, if anyone knows how to get it to include numbers mixed in
> with the
> > letters i'd like to know how.
>
> Change the loop statement to a block of code that assigns a number from,
> say, 0 to 35, to string[i].  Then use an if statement or ?: operator to
> add either 'a' or ('0'-26) to that number depending whether it is less
> than 26 or not.
>
> > - ------
> >
> > #include <stdio.h>
> > #include <sys/types.h>
> > #include <unistd.h>
> > #include <signal.h>
> > #include <stdlib.h>
> > #include <time.h>
> > #include <string.h>
> >
> > #include "version.h"
> >
> > #define SESSION_TIMEOUT 20
> >
> > #define MAX_RESPONSE 200
> > #define MAX_REQUEST 100
> >
> > #define MIN_LEN 4
> > #define MAX_LEN 9
> >
> > char *randusername()
> > {
> >         char *string;
>
> You have not initialized space to put the characters that this string
> points to, so you are putting them in, ah, unpredictable locations in
> memory.  The behavior of the program after you write to string[0] is
> undefined. I would recommend "static char string[ MAX_LEN+1 ]".
>
> >         int i, length;
> >         // randomly choose a length betweem MIN_LEN and MAX_LEN
> >         length = MIN_LEN + random() / (RAND_MAX / (MAX_LEN + 2
> - MIN_LEN))-1;
>
> >         if (string = malloc(length + 2), string == NULL)
> >                 return NULL;

Why do you assume he doesn't know what he's doing with that char* string.
Did you look farther down to see the malloc()? If he changed the code as you
suggest, it would break instantly.