C library function - memset()
Description
C library function **void memset(void str, int c, size_t n) Used to set a region of memory to a specified value.
The memset() function copies the specified value c to the first n bytes of the memory area pointed to by str; this can be used to zero a memory block or set it to a specific value.
In some cases, you need to quickly initialize a large block of memory to zero or a specific value, and memset() provides an efficient implementation.
When clearing a memory region or assigning a value to it, memset() is a commonly used utility function.
Declaration
void *memset(void *ptr, int value, size_t num);
Here is the declaration of the memset() function.
void *memset(void *str, int c, size_t n)
Parameters
- str -- a pointer to the memory area to fill.
- c -- the value to set, usually an unsigned char.
- n -- the number of bytes to set to that value.
Return Value
The function returns a pointer to the memory area str.
Notes
memset()does not perform bounds checking on the memory area pointed to by the pointerptrso you must ensure thatptrpoints to a memory area large enough to avoid out-of-bounds access.memset()The second parametervalueis usually ainttype value, but only its low 8 bits are actually used. This means values outside the range0to255may cause undefined behavior.numThe parameter indicates the number of bytes to set, usually computed viasizeof()or other means.
Example
The following example demonstrates the use of the memset() function.
Example
#include
<
stdio.h
#include
<
string.h
int
main
(
)
{
char
str
[
50
];
strcpy
(
str
,
"
This is string.h library function
"
)
;
puts
(
str
)
;
memset
(
str
,'$',
7
)
;
puts
(
str
)
;
return
(
0
)
;
}
Let's compile and run the above program, which will produce the following result:
This is string.h library function
$$$$$$$ string.h library function
Example
#include
#include
int
main
(
)
{
char
buffer
[
10
]
;
// Set the first 5 bytes of the buffer array to the character 'A', and add a string terminator
memset
(
buffer
,
'A'
,
5
)
;
buffer
[
5
]
=
'\0'
;
// Ensure the string terminator is added
printf
(
"Buffer after memset: %s\n"
,
buffer
)
;
// Zero the buffer array, using '\0' instead of 0
memset
(
buffer
,
'\0'
,
sizeof
(
buffer
)
)
;
// Use '\0' for consistency and readability
printf
(
"Buffer after memset: %s\n"
,
buffer
)
;
return
0
;
}
Let's compile and run the above program, which will produce the following result:
Buffer after memset: AAAAA
Buffer after memset:
C Standard Library -