memset(3)
C library function
Fills the first n bytes of a memory area with one byte value and returns the address of the area. Handy for setting a buffer to zero.
#include <string.h>
void *memset(void *s, int c, size_t n);Description
memset writes the same value into the first n bytes of the area that s points to. The C23 standard spells out the conversion: the function “copies the value of c (converted to an unsigned char) into each of the first n characters”. c is an int, but only its low 8 bits count. That is why memset(buf, 0, n) sets everything to zero, and memset(buf, '-', n) fills the area with dashes.
The most common use is zeroing a buffer or a structure right after allocating it, when calloc(3) does not fit (for a stack variable, for instance). Watch out for a frequent misconception: memset(array, 1, n) does not set each int to 1, it sets each byte to 0x01, so each int becomes 0x01010101. memset works in bytes, not in elements.
Return value
memset returns s, the address you gave it. As with memcpy and memmove, the value is mostly there for chaining calls.
Example
#include <stdio.h>#include <string.h>
int main(void){ char line[6];
memset(line, '-', 5); line[5] = '\0'; printf("%s\n", line); return 0;}$ gcc -Wall -Wextra -g memset.c -o memset$ ./memset-----Pitfalls
Expecting to fill an array of
intwith a value: only the low byte ofcis used, repeated in every byte. Zero is the only value that gives the expected result for every type.Mixing up the argument order: it is
memset(s, c, n), the value before the size. Many people expect the opposite.Counting on
memset(p, 0, n)to erase a secret you are about to free: the compiler may remove the call if it decides the area is not used afterwards. C23 addsmemset_explicitfor exactly that need.Passing a size in elements instead of bytes: for an array of
int, it isn * sizeof(int).
memset
Write gm_memset, which stores the low byte of c in exactly n bytes and returns the pointer it was given, not the end of the area.