[PATCH] add memrchr(3)

Eric Blake eblake@redhat.com
Thu May 10 08:35:00 GMT 2012


On 05/09/2012 12:42 PM, Gregory Pietsch wrote:
> I have been thinking of how many crazy ways there are to implement
> memrchr as a result of this discussion.
> 
> First, the usual way:
> 
> #include<string.h>
>  /* memrchr */
>  void  *(memrchr)(const  void  *s,  int  c,  size_t  n)
>  {
>      const  unsigned  char  *src=  s;
>      unsigned  char  uc=  c;
> 
>      src += n - 1;
>       while  (src  >=  (const unsigned char *) s)  {
>          if  (*src==  uc)
>              return  (void  *)  src;
>          --src;
>      }
>      return  NULL;
>  }

Probably good enough, if that's the way BSD did it (but in that case,
copy the BSD file as a reference implementation).

> 
> 
> I was also thinking recursion. Maybe that would be faster:
> 
> #include<string.h>
>  /* memrchr */
>  void  *(memrchr)(const  void  *s,  int  c,  size_t  n)
>  {
>      const  unsigned  char  *src=  s;
>      unsigned  char  uc=  c;
> 
>      return n ? (src[n - 1] == uc ? (void *) (src + n - 1)
>        : memrchr (s, c, n - 1)) : 0;

No.  Unless the compiler optimizes the tail-recursion out, this is
slower, and risks overflowing the user's stack when handed malicious
data.  Never a good idea to use recursion in libc, when iteration will do.

-- 
Eric Blake   eblake@redhat.com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 620 bytes
Desc: OpenPGP digital signature
URL: <http://sourceware.org/pipermail/newlib/attachments/20120510/a36372f3/attachment.sig>


More information about the Newlib mailing list