C++ memchr() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
<cstring>

Definition

In C++, memchr() searches a byte range for the first matching byte value.

Include <cstring>.

This guide shows the C library helper in a C++ .cpp program with std::cout. Prefer std::string for new text code; keep these APIs for C interop and interviews.

Syntax

Pass pointer, value, and length.

C++
const void* p = std::memchr(buf, 'a', n);
CallWhat it does
std::memchr(ptr, ch, n)Pointer to first match, or null.

Unlike strchr, memchr can look past embedded null bytes because it uses a length.

Library declarations
C++
void* memchr(void* ptr, int ch, size_t n);
const void* memchr(const void* ptr, int ch, size_t n);

Parameters

ParameterDescription
ptrStart of memory.
chByte to find.
nHow many bytes to examine.

Return Value

Return ValueDescription
pointer or nullAddress of the first match, else nullptr.

C++ Examples

Example 1 — Basic memchr()

Find character b.

C++
#include <cstring>
#include <iostream>

int main() {
    char buf[] = "abc";
    const void* p = std::memchr(buf, 'b', 3);
    if (p) {
        std::cout << *static_cast<const char*>(p) << '\\n';
    }
    return 0;
}

How It Works

  1. Search examines three bytes.
  2. Match pointer refers to 'b'.
  3. Cast and print that character.

Example 2 — memchr Null

Missing byte yields nullptr.

C++
#include <cstring>
#include <iostream>

int main() {
    char buf[] = "xyz";
    const void* p = std::memchr(buf, 'a', 3);
    std::cout << (p ? "yes" : "no") << '\\n';
    return 0;
}

How It Works

  1. No 'a' exists.
  2. memchr returns null.
  3. Branch prints no.

Example 3 — Search Past Null

Length-based search finds a byte after 0.

C++
#include <cstring>
#include <iostream>

int main() {
    char buf[4] = {'a', '\\0', 'b', 'c'};
    const void* p = std::memchr(buf, 'b', 4);
    std::cout << (p ? "found" : "no") << '\\n';
    return 0;
}

How It Works

  1. strchr would stop at the embedded null.
  2. memchr uses the length 4.
  3. It finds 'b'.

Frequently Asked Questions

Finds the first matching byte in n bytes of memory.
nullptr.
<cstring>.
strchr stops at \0; memchr uses an explicit length.
Yes—to use the pointer as char* or another type.

Next: memcmp()

Keep going through the string functions. Compare two byte blocks; return <0, 0, or >0.

memcmp() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful