RE: generic strncpy - off-by-one error

Peter Kjellerstedt
2003-08-16T09:24:55Z

> -----Original Message-----
> From: Daniel Forrest [mailto:forrest@lmcg.wisc.edu]
> Sent: Saturday, August 16, 2003 10:41
> To: Peter Kjellerstedt
> Cc: 'Timothy Miller'; 'Willy Tarreau'; linux-kernel mailing list
> Subject: Re: generic strncpy - off-by-one error
>
> On Sat, Aug 16, 2003 at 10:15:14AM +0200, Peter Kjellerstedt wrote:
> >
> > Here is the code that I used:
> >
> > char *strncpy(char *dest, const char *src, size_t count)
> > {
> > char *tmp = dest;
> >
> > while (count && *src) {
> > *tmp++ = *src++;
> > count--;
> > }
> >
> > if (count) {
> > size_t count2;
> >
> > while (count & (sizeof(long) - 1)) {
>
> Shouldn't this be:
>
> while (tmp & (sizeof(long) - 1)) {

Actually, it should be:

while (count && ((long)tmp & (sizeof(long) - 1)))

> > *tmp++ = '\0';
> > count--;
> > }
> >
> > count2 = count / sizeof(long);
> > while (count2) {
> > *((long *)tmp)++ = '\0';
> > count2--;
> > }
> >
> > count &= (sizeof(long) - 1);
> > while (count) {
> > *tmp++ = '\0';
> > count--;
> > }
> > }
> >
> > return dest;
> > }
>
> --
> Dan

//Peter