[TAG] Compliments to you all.
Jason Creighton
androflux at softhome.net
Tue Jun 8 04:11:39 MSD 2004
On Mon, 7 Jun 2004 11:35:42 -0400,
Ben Okopnik <ben at callahans.org> wrote:
> On Sat, Jun 05, 2004 at 08:44:32PM -0600, Jason Creighton wrote:
> > On Fri, 4 Jun 2004 19:46:00 -0400,
> > Ben Okopnik <ben at callahans.org> wrote:
> >
> > > Tell you what - here, take a look at this code, and see if you can
> > > figure out what's wrong with it (note that input length _is_ being
> > > validated!):
> >
> > Okay, I tried to figure it out without reading the other replies, and
> > then I tried to figure it out with reading the other replies. So what
> > we're saying here is that the "i <= SIZE" test will allow something like
> >
> > buf[SIZE] = p1[SIZE]
> >
> > to be executed when in reality we should have stopped at SIZE-1 due to
> > zero-based indexing?
>
> Nope; see my answer to Steve Brown.
Hmm...you're right. Even if you stop copying at the right time, buf1
still isn't NUL terminated. So, is this version okay?
``
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
int main(int argc, char *argv[])
{
int i;
char *p1, *p2;
char *buf1 = malloc(SIZE);
char *buf2 = malloc(SIZE);
if (argc != 3)
exit(1);
p1 = argv[1], p2 = argv[2];
printf("p1 is at %p\n", p1);
strncpy(buf2, p2, SIZE);
for (i = 0; i < SIZE && p1[i] != '\0'; i++)
buf1[i] = p1[i];
/* slap a NUL on there */
buf1[SIZE-1] = '\0';
printf("length of buf1 is %d\n", strlen(buf1));
free(buf1);
free(buf2);
return 0;
}
''
Jason Creighton
More information about the TAG
mailing list