On Fri, 2003-11-28 at 01:40, YOSHIFUJI Hideaki / åèèæ wrote:
> In article <20031128.092642.47232575.yoshfuji@xxxxxxxxxxxxxx> (at Fri, 28 Nov
> 2003 09:26:42 +0900 (JST)), YOSHIFUJI Hideaki / åèèæ
> <yoshfuji@xxxxxxxxxxxxxx> says:
>
> > > 3) if (len)
> > > strncpy(dst, src, len - 1);
> > > dst[len] = 0;
>
> grr, another mistake...:
>
> if (len) {
> strncpy(dst, src, len - 1);
> dst[len - 1];
> }
>
> ----------------
> 1) use strlcpy0(dst, src, len)
>
> size_t strlcpy0(char *dst, const char *src, size_t maxlen)
> {
> size_t len = strlcpy(dst, src, maxlen);
> if (likely(maxlen != 0) && len < maxlen - 1)
> memset(dst + len + 1, 0, maxlen - len - 1);
> }
>
> 2a) use strncpy0(dst, src, len)
>
> char *strncpy0(char *dst, const char *src, size_t maxlen)
> {
> memset(dst, 0, maxlen);
> if (likely(maxlen != 0))
> strncpy(dst, src, maxlen - 1);
> }
>
> 2b) fix strncpy() to zero-out rest of destination buffer
> and use strncpy0(dst, src, len)
>
> char *strncpy0(char *dst, const char *src, size_t maxlen)
> {
> if (likely(maxlen != 0)) {
> strncpy(dst, src, maxlen - 1);
> dst[maxlen - 1] = 0;
> }
> }
>
>
> I prefer 1 > 2b >> 2a.
What about coding a new function str0cpy()?
/**
* str0cpy - Copy a length-limited, %NUL-terminated string
* @dest: Where to copy the string to
* @src: Where to copy the string from
* @count: The maximum number of bytes to copy
*/
char * str0cpy(char * dest,const char *src,size_t count)
{
if (count) {
char *tmp = dest;
count--;
while (count) {
if ((*tmp = *src) != 0) src++;
tmp++;
count--;
}
*tmp = 0;
}
return dest;
}
It behaves like strncpy() but correctly null-terminates the string in
every case.
|