C++ memset() Function

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

Definition

In C++, memset() fills a memory block with one byte value repeated.

Often used to zero a buffer. 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, byte value, and count.

C++
std::memset(buf, 0, sizeof buf);
CallWhat it does
std::memset(dest, value, n)Set n bytes to value.

value is converted to unsigned char. Filling ints with memset(1) does not set each int to 1—only each byte.

Library declarations
C++
void* memset(void* dest, int ch, size_t n);

Parameters

ParameterDescription
destStart of the buffer.
chByte value (0–255 after conversion).
nNumber of bytes.

Return Value

Return ValueDescription
void*Equals dest.

C++ Examples

Example 1 — Basic memset()

Clear a char buffer.

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

int main() {
    char buf[5];
    std::memset(buf, 0, sizeof buf);
    buf[0] = 'A';
    std::cout << buf << '\\n';
    return 0;
}

How It Works

  1. All bytes become 0.
  2. Setting buf[0] makes a short C-string.
  3. Print shows A.

Example 2 — Fill With Byte

Fill with asterisks then terminate.

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

int main() {
    char buf[4];
    std::memset(buf, '*', 3);
    buf[3] = '\\0';
    std::cout << buf << '\\n';
    return 0;
}

How It Works

  1. Three bytes become '*'.
  2. We add a null terminator manually.
  3. Print shows three stars.

Example 3 — Zero an Int Array

Set all bytes of an int array to 0.

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

int main() {
    int a[3];
    std::memset(a, 0, sizeof a);
    std::cout << a[0] << a[1] << a[2] << '\\n';
    return 0;
}

How It Works

  1. Zero bytes mean zero ints on common platforms.
  2. All three elements print 0.
  3. This pattern is for trivial types only.

Frequently Asked Questions

Fills n bytes with a repeated byte value.
memset(a, 1, sizeof a) sets every byte to 1, not each int to 1.
<cstring>.
std::fill / std::fill_n for typed ranges.
C23/C++23-ish intent to avoid dead-store removal for sensitive clears—support varies.

Next: memset_explicit()

Keep going through the string functions. Fill memory with intent that the store is not optimized away (C23).

memset_explicit() 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.

9 people found this page helpful