qemu-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Qemu-devel] [libfdt][PATCH v2] implement strnlen for systems that n


From: Programmingkid
Subject: Re: [Qemu-devel] [libfdt][PATCH v2] implement strnlen for systems that need it
Date: Sun, 22 Oct 2017 15:52:43 -0400

> On Oct 22, 2017, at 3:06 PM, Ian Lepore <address@hidden> wrote:
> 
> On Sun, 2017-10-22 at 10:41 -0400, Programmingkid wrote:
>>> 
>>> On Oct 22, 2017, at 1:33 AM, David Gibson  wrote:
>>> 
>>> On Fri, Oct 20, 2017 at 04:44:58PM -0700, Richard Henderson wrote:
>>>> 
>>>> On 10/20/2017 10:55 AM, John Arbuckle wrote:
>>>>> 
>>>>> +static inline size_t strnlen(const char *string, size_t max_count)
>>>>> +{
>>>>> +    size_t count;
>>>>> +    for (count = 0; count < max_count; count++) {
>>>>> +        if (string[count] == '\0') {
>>>>> +            break;
>>>>> +        }
>>>>> +    }
>>>>> +    return count;
>>>> Not to nitpick, but
>>>> 
>>>>  const char *p = memchr(string, 0, max_count);
>>>>  return p ? max_count : p - string;
>>> Richard's right, that's definitely a better implementation.
>> His implementation is smaller, but this one is even smaller. Plus it uses 
>> the familiar strlen() function:
>> 
>> size_t strnlen(const char *string, size_t max_count)
>> {
>>     return strlen(string) < max_count ? strlen(string) : max_count;
>> }
> 
> That is not a proper implementation of strnlen(), which is not supposed
> to access any source-string bytes beyond max_count.
> 
> -- Ian

http://pubs.opengroup.org/onlinepubs/9699919799/functions/strlen.html
This specification document should help anyone who wants more info.

The first implementation using the loop would never access anything beyond 
max_count. My second implementation does go beyond max_count. The 
implementation using memchr() will probably live up the requirement so I guess 
it wins.

Thank you Ian for this information. 




reply via email to

[Prev in Thread] Current Thread [Next in Thread]