Namespaces
Variants
Views
Actions

memset, memset_s

From cppreference.com
< c‎ | string‎ | byte
Defined in header <string.h>
void *memset( void *dest, int ch, size_t count );
(1)
errno_t memset_s( void *dest, rsize_t destsz, int ch, rsize_t count )
(2) (since C11)
1) Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest.
2) Same as (1), except that the following errors are detected at runtime and call the currently installed constraint handler function:
  • dest is a null pointer
  • destsz or count is greater than RSIZE_MAX
  • count is greater than destsz
As all bounds-checked functions, memset_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including string.h.

Contents

[edit] Parameters

dest - pointer to the object to fill
ch - fill byte
count - number of bytes to fill
destsz - size of the destination array

[edit] Return value

1) A copy of dest
2) zero on success, non-zero on error

[edit] Notes

memset may be optimized away (under the as-if rules) if the object modified by this function is not accessed again for the rest of its lifetime. For that reason, this function cannot be used to scrub memory (e.g. to fill an array that stored a password with zeroes). This optimization is prohibited for memset_s: it is guaranteed to perform the memory write.

[edit] Example

#include <stdio.h>
#include <string.h>
 
int main(void)
{
    char str[] = "ghghghghghghghghghghgh";
    puts(str);
    memset(str,'a',5);
    puts(str);
}

Output:

ghghghghghghghghghghgh
aaaaahghghghghghghghgh

[edit] References

  • C11 standard (ISO/IEC 9899:2011):
  • 7.24.6.1 The memset function (p: 371)
  • K.3.7.4.1 The memset_s function (p: 621-622)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.21.6.1 The memset function (p: 333)
  • C89/C90 standard (ISO/IEC 9899:1990):

[edit] See also

copies one buffer to another
(function) [edit]
copies the given wide character to every position in a wide character array
(function) [edit]