The memset() function from <string.h> fills a memory block with a single byte value repeated n times. It is most often used to zero out buffers (memset(ptr, 0, n)) before use, but it can also pad strings or initialize arrays with a chosen character.
01
Fill n Bytes
Same value.
02
Zero Memory
value = 0
03
Returns ptr
Same pointer.
04
unsigned char
Byte conversion.
05
Not strcpy
No copy from src.
06
Watch \0
Strings need care.
Fundamentals
Definition and Usage
In C, memset() is declared in <string.h>. It writes the byte value (converted to unsigned char) into each of the first n bytes starting at ptr, then returns ptr.
Unlike memcpy() or memmove(), memset() does not copy from another buffer—it generates bytes from the value you supply. For C-strings, zero-filling with memset(str, 0, sizeof str) clears the buffer to empty strings. Filling with other characters requires leaving space for '\0' if you plan to use printf("%s").
💡
Beginner Tip
memset(array, 'A', sizeof array) fills every byte with 'A'—there is no automatic null terminator. Either reserve the last byte for '\0' or use memset(array, 0, sizeof array) when you want a safe empty string.
Foundation
📝 Syntax
The standard library declaration:
C
void *memset(void *ptr, int value, size_t n);
Parameters
ptr — pointer to the memory block to fill.
value — byte value to write, converted to unsigned char (commonly 0 or a character like 'A').
n — number of bytes to set.
Return Value
Returns ptr (the pointer to the filled block).
Header
#include <string.h>
Cheat Sheet
⚡ Quick Reference
Goal
Call
Notes
Zero entire buffer
memset(buf, 0, sizeof buf)
Empty C-string
Clear n bytes
memset(ptr, 0, n)
Common init pattern
Fill with character
memset(buf, '*', n)
Add '\0' if needed
Pad then terminate
memset(buf, 'A', size-1); buf[size-1]='\0'
Safe for %s
Return value
ptr
Often ignored
Zero-fill
memset(p, 0, n)
Most common use
Char fill
memset(p, 'X', n)
Repeat one byte
Array
memset(a, 0, sizeof a)
Whole local array
Not for copy
memcpy / memmove
Copy from elsewhere
Hands-On
Examples Gallery
Compile with gcc memset.c -std=c11 -o memset. Examples show safe zero-fill, character padding, and clearing buffers before reuse.
📚 Getting Started
Initialize a buffer to zero—the most common memset pattern.
Example 1 — Zero-Fill a Character Buffer
Clear a char array so it starts as an empty, valid C-string.
Every byte becomes 0, so the first character is '\0'. This is safer than leaving stack garbage in a buffer before reading user input with fgets or similar.
Example 2 — Fill with a Character (Safely)
Pad a buffer with 'A' but keep a null terminator at the end.
We fill 19 bytes with 'A' and manually set index 19 to '\0'. Filling all 20 bytes with 'A' (as some tutorials show) leaves no terminator and makes printf("%s") unsafe.
📈 Practical Patterns
Reuse buffers, initialize structs, and contrast with copy functions.
Example 3 — Clear a Buffer Before Reuse
Wipe old data before storing new input—a simple security and correctness habit.
Zeroing the full buffer removes leftover characters from the old string. strcpy then writes the new text starting at index 0. For sensitive data, zero-fill helps avoid leaking old bytes (though dedicated secure erase may be needed for secrets).
All bytes of the struct become zero: integers are 0, floats are 0.0, and the name array is an empty string. In C++, prefer value initialization; in C, memset(&s, 0, sizeof s) is a common idiom.
Example 5 — memset() vs memcpy()
memset generates bytes; memcpy copies from another location.
After memset + memcpy: Hello
After memset dashes: -----
How It Works
Typical workflow: memset clears the buffer, memcpy copies string content from src. Later, memset(dest, '-', 5) overwrites the first five characters with dashes (with manual null termination).
Applications
🚀 Common Use Cases
Zero initialization — clear stack buffers, structs, and arrays before first use.
Reset buffers — wipe old string data before reading new input.
Padding — fill a region with a repeated character (with proper '\0' handling).
Network / binary frames — set reserved header bytes to zero.
Embedded systems — initialize RAM regions at startup.
🧠 How memset() Works
1
You pass ptr, value, and n
The function receives the start address, the byte to write, and how many bytes to fill.
Input
2
Convert value to byte
value is cast to unsigned char before each write.
Convert
3
Write n times
Each of the first n bytes at ptr is set to that byte.
Fill
=
🛠
Return ptr
Memory is filled with identical bytes—often all zeros for initialization.
Important
📝 Notes
memset does not copy from another buffer—use memcpy or memmove for that.
Filling an entire char array with a non-zero character does not create a valid C-string unless you add '\0'.
memset(ptr, 0, n) is the standard way to zero memory; only the low byte of value is used.
Do not call memset on memory you must not write (read-only sections, invalid pointers).
For floating-point structs, zero bits often mean 0.0 but padding and representation quirks exist—zeroing is still widely used for plain C structs.
Performance
⚡ Optimization
Standard library memset() is highly optimized—often using wide stores for large blocks. Prefer it over manual loops for zeroing or filling memory. For very small fixed sizes, compilers may inline memset calls automatically.
Wrap Up
Conclusion
memset() is the standard way to fill memory with a repeated byte value. Use it to zero buffers, reset strings, and initialize structs—and remember to handle null terminators when treating char arrays as C-strings.
That completes the core mem* family in this series: memchr, memcmp, memcpy, memmove, and memset. Practice the examples, then explore more C string functions as they are added to the site.
Reserve the last byte for '\0' when padding with chars
Zero structs with memset(&s, 0, sizeof s)
Clear sensitive buffers before freeing when appropriate
Pair zero-fill with memcpy for clean string setup
❌ Don’t
Print with %s after filling every byte with non-zero chars
Use memset to copy from another string
Write past the end of the allocated buffer
Assume memset sets multi-byte integers beyond zero safely in all cases
Rely on memset alone to erase secrets from memory in high-security code
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about memset()
Use these points whenever you initialize memory in C.
5
Core concepts
🛠01
Fill n Bytes
Same value.
Basics
🔒02
Zero with 0
Most common.
Pattern
🔢03
Returns ptr
Same address.
Return
📈04
Not a copy
vs memcpy.
Compare
💬05
Mind \0
String safety.
Strings
❓ Frequently Asked Questions
memset() sets the first n bytes of a memory block to a specified byte value. It returns the pointer to the block. The most common use is memset(ptr, 0, n) to zero out memory.
void* memset(void* ptr, int value, size_t n); Include <string.h>. ptr points to the memory to fill, value is converted to unsigned char, and n is how many bytes to set.
It returns ptr—the same pointer passed as the first argument. Many programs ignore the return value.
Yes. memset(str, 0, size) sets every byte to zero, producing an empty C-string if the buffer is at least one byte long. To fill with a character like 'A', leave room for '\0' or set the last byte manually.
memset() writes the same byte value repeatedly into a block—it does not copy from another location. memcpy() copies n bytes from a source buffer to a destination.
No. It only writes the byte value you specify n times. If you fill an entire char array with 'A' and print with %s without a '\0', behavior is undefined. Use memset(ptr, 0, n) for zero-fill, or set str[n-1] = '\0' when filling with other characters.
Did you know?
C++11 offers = {} and default member initialization, but in C the idiom memset(&obj, 0, sizeof obj) remains ubiquitous for zeroing structs and buffers before use—especially in systems and embedded code.