lkml.org 
[lkml]   [2003]   [Aug]   [12]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
SubjectRe: generic strncpy - off-by-one error
From
Date
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;
}
////////////////////////////////////////////////////////////

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/

\
 
 \ /
  Last update: 2005-03-22 13:47    [from the cache]
©2003-2011 Jasper Spaans