[PATCH] Improve memmem.

Paul Eggert eggert@cs.ucla.edu
Wed May 13 16:31:00 GMT 2015


Ondřej Bílka wrote:
> +  if (needle_len == 1)
> +    return memchr (haystack, needle[0], haystack_end - haystack);
> +
> +  while ((haystack = memchr (haystack, needle[0], haystack_end - haystack)))
> +    {
> +      if (haystack[1] == needle[1]
> +          && (needle_len == 2 || haystack[2] == needle[2]))
> +        {
> +          if (needle_len == 2)
> +            return haystack;
> +
> +          if (!memcmp (haystack + 2, needle + 2, needle_len - 2))
> +            return haystack;
> +          else
> +            goto slow_path;
> +        }
> +      haystack++;
> +    }
> +
> +  return NULL;
> +
> +  slow_path:;

First, that "haystack[1] == needle[1]" could access past the end of the 
haystack.  Second, can't this be rewritten to avoid that ugly goto?  Something 
like the attached, perhaps.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: memmem-fragment.c
Type: text/x-csrc
Size: 412 bytes
Desc: not available
URL: <http://sourceware.org/pipermail/libc-alpha/attachments/20150513/924d04ab/attachment.bin>


More information about the Libc-alpha mailing list