Protecting the world

from criminally bad code

memchr

Synopsis

#include <string.h>

#ifndef __cplusplus

void* memchr(const void* s,int c,size_t n);

#else

void* memchr(void* s,int c);
const void* memchr(const void* s,int c,size_t n);

#endif

Description

The memchr function searches for a byte with a given value within a block of raw memory. It returns a pointer to the first instance found, or null if the search failed.

Pitfalls

Const incorrectness

In C, memchr has the ability to convert a const pointer into a non-const pointer. There is a reason for this behaviour, but it is open to misuse and it can prevent the compiler from detecting some types of error.

See the page ‘Const-incorrect standard library functions’ for a more detailed discussion of this issue.

Portability

  •  C90
  •  C99
  •  C++98
  •  C++11

In C++, use of the header <string.h> is deprecated in favour of <cstring>.

Further reading

  • The memchr function, Programming languages — C, ISO/IEC 9899:1999, §7.21.5.1, p329
  • memchr, The Open Group Base Specifications, Issue 7, The Open Group, 2008
  • memchr(3), Linux Programmer’s Manual, The Linux man-pages project
  • Search Functions, The GNU C Library Reference Manual, The GNU Project