bug-cvs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: CVS update: MODIFIED: src ...


From: Paul Edwards
Subject: Re: CVS update: MODIFIED: src ...
Date: Sat, 26 Jul 2003 02:31:23 GMT

"Derek Robert Price" <address@hidden> wrote in message news:address@hidden
> John Tytgat wrote:
>
> > address@hidden wrote:
> >
> >>   strip_trailing_newlines (char *str)
> >>   {
> >>  -    int len;
> >>  -    len = strlen (str) - 1;
> >>  +    int len, origlen;
> >>  +    len = origlen = strlen (str) - 1;
> >>         while (str[len] == '\n')
> >>       str[len--] = '\0';
> >>  +
> >>  +    return len != origlen;
> >>   }
> >>
> > What if str points in the middle of a zero terminated char array full
> > of '\n' chars ? len will go negative.  I admit it is unlikely but I
> > would change :
> >
> > while (str[len] == '\n')
> >
> > into
> >
> > while (str[len] == '\n' && len >= 0)
>
> Hrm.  I guess an empty line, with only a newline, could have attempted
> to walk back into unknown memory space before the string anyhow.  Thanks!

Actually, on an empty string, the above code will try to
access str[-1], which could cause a memory violation
(read, not write).

And strlen() actually returns a size_t, ie normally an unsigned int,
so if you do it properly, you would actually go:

strip_trailing_newlines (char *str)
{
    size_t len, origlen;
    len = origlen = strlen (str);

    while (len > 0 && str[--len] == '\n' )
    {
        str[len] = '\0';
    }
    return len != origlen;
}




reply via email to

[Prev in Thread] Current Thread [Next in Thread]