Re: generic strncpy - off-by-one error

Albert Cahalan
2003-08-13T02:28:55Z

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;
}

static char ref[32];
static char hmm[32];

static char s0[] = "";
static char s1[] = "1";
static char s2[] = "12";
static char s6[] = "123456";
static char s7[] = "1234567";
static char s8[] = "12345678";
static char s9[] = "123456789";

static void tester(const char *src, size_t count){
memset(ref,'%',sizeof ref);
memset(hmm,'%',sizeof hmm);
strncpy (ref+2,src,count);
strncpy_good(hmm+2,src,count);
if(memcmp(ref,hmm,sizeof hmm)){
printf("error @ size %d\n",(int)count);
}
}

int main(int argc, char *argv[]){
int i = 15;
while(i--){
tester(s0,i);
tester(s1,i);
tester(s2,i);
tester(s6,i);
tester(s7,i);
tester(s8,i);
tester(s9,i);
}
return 0;
}
////////////////////////////////////////////////////////////