[FFmpeg-devel] [RFC] av_strlcpy instead of pstrcpy

Måns Rullgård mans
Sat Jun 23 21:33:35 CEST 2007


Michael Niedermayer <michaelni at gmx.at> writes:

> Hi
>
> On Sat, Jun 23, 2007 at 05:10:26PM +0200, Reimar D?ffinger wrote:
>> Hello,
>> attached incomplete patch (no uses changed) would replace pstrcpy and
>> pstrcat by av_strlcpy and av_strlcat which behave like the (BSD-only)
>> strlcpy and strlcat functions (documentation here:
>> http://developer.apple.com/documentation/Darwin/Reference/Manpages/man3/strlcpy.3.html).
>> While I don't think we will ever really need the "return value vodoo" ;-) of these
>> functions it seems preferable to not have yet another different
>> implementation (of course that is only true if you check that my
>> implementations really are right).
>> It might also allow to use the real system functions if available like
>> MPlayer does (but of course in a less ugly-hackish way).
>
> iam in favor of this in principle ...
>
> [...]
>> -void pstrcpy(char *buf, int buf_size, const char *str)
>> +size_t av_strlcpy(char *buf, const char *str, size_t buf_size)
>>  {
>> +    size_t i = 0;
>>      if (buf_size <= 0)
>> -        return;
>> +        goto out;
>>  
>> -    while (buf_size-- > 1 && *str)
>> -        *buf++ = *str++;
>> -    *buf = 0;
>> +    while (buf_size-- > 1 && *str) {
>> +        buf[i] = str[i];
>
> uhm, *str and src[i]?
>
>> +    }
>> +    buf[i] = 0;
>> +out:
>> +    while (str[i]) i++;
>> +    return i;
>
> maybe the following is less buggy (or maybe not ...)
>
> size_t av_strlcpy(char *buf, const char *str, size_t buf_size)
> {
>     const char *org= src;
>     while (buf_size-- > 1 && *str)
>         *buf++ = *str++;
>     if(buf_size>0)
>         *buf = 0;
>     return src-org+strlen(src);
> }

This breaks if buf_size == 0 (size_t is unsigned).

My take:

size_t av_strlcpy(char *dst, const char *src, size_t size)
{
    size_t len = 0;
    while (++len < size && *src)
        *dst++ = *src++;
    if (len <= size)
        *dst = 0;
    return len + strlen(src) - 1;
}

size_t av_strlcat(char *dst, const char *src, size_t size)
{
    size_t len = strlen(dst);
    if (size <= len + 1)
        return len + strlen(src);
    return len + av_strlcpy(dst + len, src, size - len);
}

Did I overlook anything?

-- 
M?ns Rullg?rd
mans at mansr.com




More information about the ffmpeg-devel mailing list