C Reference ยท string.h
C memset() function
Reference for C memset(): fill a block with one byte value, why it is right for zeroing but wrong for int arrays, and the dead-store problem with secrets.
memset() sets every byte in a block of memory to the same value. Its two everyday jobs are zeroing a buffer or structure and filling a character buffer with a single character. The value you pass is converted to unsigned char, so it always affects whole bytes.
That byte-wise behavior is a common trap: memset(array, 1, sizeof array) on an int array does not give you ones, it gives you 0x01010101 in every element.
#include <string.h> void *memset(void *s, int c, size_t n);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
void *memset(void *s, int c, size_t n);
| Name | Description |
|---|---|
s |
Start of the block to fill. |
c |
The value, converted to unsigned char. |
n |
The number of bytes to set. |
Returns: s.
Errors / undefined behavior: the block must be valid for n bytes. NULL is undefined, even for n == 0.
Usage notes
- Zero is special. All-bits-zero is the zero value for every integer type, and the value
0.0for floating-point types on all mainstream platforms (IEEE 754). For pointers, all-bits-zero is a null pointer on common systems but the standard does not promise it; assigningNULLis always correct. - Other values work only on single bytes and on integers whose bytes are all equal, such as
0or-1(0xFF). They do not setintordoubleelements to a given number. Use a loop. sizeofpitfalls.sizeof arrayworks only on a real array. For a pointer it is the pointer size. Writesizeof *ptr * countfor allocated memory.- Initialization alternatives.
= {0}(and= {}in C23) zero-initializes arrays and structs at declaration and is clearer.callocreturns zeroed memory.memsetis for resetting an existing object. - Padding bytes are set too, which is useful before you write a struct to a file or compare it with
memcmp. - Wiping secrets. A compiler may delete a
memseton a buffer that is never read again (dead store elimination), leaving passwords in memory. Usememset_explicit()(C23, not in glibc 2.28),explicit_bzero()(glibc, BSD), ormemset_s()(optional Annex K) when clearing sensitive data. - Strings:
memsetdoes not terminate anything. After filling a character buffer, write the'\0'yourself. - Cost is linear and very fast; large fills use vector instructions.
Related
memcpy,memcmp,calloc, Designated initializers- Lessons: Arrays, Dynamic memory