[TAG] Compliments to you all.

Jason Creighton androflux at softhome.net
Thu Jun 10 08:20:30 MSD 2004


On Wed, 9 Jun 2004 14:04:37 -0400, 
Ben Okopnik <ben at callahans.org> wrote:

> On Mon, Jun 07, 2004 at 06:11:39PM -0600, Jason Creighton wrote:
> > 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';
>  
> What if the string length _is_ equal to SIZE? Or, if it's not, what if
> the length really matters in some further calculations? In the first
> case, you'd lose content. In the second case, you've just made the
> length of "buf1" 99 no matter what - which also means that the content
> between the end of the actual input and the NUL is random garbage that
> was in that memory location.

Yes, of course. I thought that, with the example you gave, it was okay
for this program to truncate input. In the Real World, this is almost
never okay, so it would be better, as you say,  just to bomb out with an
error message to the effect of "The person who coded this was too lazy
to do it right[1]".

Of course, the demonstration here was "arbitrary input", not "command
line args". If it was command line arguments, it would be trivial to
strlen() the argument, malloc() enough space and then copy it over.
After all, getting a string from argv that wasn't NUL-terminated would
indicate something seriously broken.

[1] Where "doing it right" would be something Really Clever involving
dynamically changing the size of your string with realloc() as you grab
the data in bits and pieces from wherever you're getting it. Or just
finding some library that does it for you.

Jason Creighton




More information about the TAG mailing list