netdev
[Top] [All Lists]

Re: [PATCH 2.6]: IPv6: strcpy -> strlcpy

To: YOSHIFUJI Hideaki / åèèæ <yoshfuji@xxxxxxxxxxxxxx>
Subject: Re: [PATCH 2.6]: IPv6: strcpy -> strlcpy
From: Felipe Alfaro Solana <felipe_alfaro@xxxxxxxxxxxxx>
Date: Fri, 28 Nov 2003 10:54:33 +0100
Cc: rmk+lkml@xxxxxxxxxxxxxxxx, davem@xxxxxxxxxx, Linux Kernel Mailinglist <linux-kernel@xxxxxxxxxxxxxxx>, netdev@xxxxxxxxxxx
In-reply-to: <20031128.094022.106776635.yoshfuji@linux-ipv6.org>
References: <1069974209.5349.7.camel@teapot.felipe-alfaro.com> <20031128.092326.39861126.yoshfuji@linux-ipv6.org> <20031128.092642.47232575.yoshfuji@linux-ipv6.org> <20031128.094022.106776635.yoshfuji@linux-ipv6.org>
Sender: netdev-bounce@xxxxxxxxxxx
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.



<Prev in Thread] Current Thread [Next in Thread>