Re: generic strncpy - off-by-one error

Albert Cahalan
2003-08-13T03:49:10Z

On Tue, 2003-08-12 at 22:47, Erik Andersen wrote:
> On Tue Aug 12, 2003 at 10:18:21PM -0400, Albert Cahalan wrote:
> > You're all wrong. This is some kind of programming
> > test for sure!
> >
> > Let us imagine that glibc has a correct version.
> > By exhaustive testing, I found a version that works.
> > Here it is, along with the test code:
> >
> > //////////////////////////////////////////////////////
> > #define _GNU_SOURCE
> > #include <string.h>
> > #include <stdlib.h>
> > #include <stdio.h>
> >
> > // first correct implementation!
> > char * strncpy_good(char *dest, const char *src, size_t count){
> > char *tmp = dest;
> > memset(dest,'\0',count);
> > while (count-- && (*tmp++ = *src++))
> > ;
> > return dest;
> > }
>
> char *strncpy(char * s1, const char * s2, size_t n)
> {
> register char *s = s1;
> while (n) {
> if ((*s = *s2) != 0) s2++;
> ++s;
> --n;
> }
> return s1;
> }

That's excellent. On ppc I count 12 instructions,
4 of which would go away for typical usage if inlined.
Annoyingly, gcc doesn't get the same assembly from my
attempt at that general idea:

char * strncpy_5(char *dest, const char *src, size_t count){
char *tmp = dest;
while (count--){
if(( *tmp++ = *src )) src++;
}
return dest;
}

I suppose that gcc could use a bug report.