memset() Function
The memset()
function in C is used to fill a block of memory with a specific byte value. It is commonly employed to initialize or reset memory areas before they are used, ensuring that the memory holds a known state.
Syntax of memset()
void *memset(void *ptr, int value, size_t num);
Parameters
Parameter | Description |
---|---|
ptr | Pointer to the block of memory to fill. |
value | Value to be set, passed as an int but converted to an unsigned char. |
num | Number of bytes to be set. |
The function sets each byte in the specified memory block to the given value. Because the operation is performed byte by byte, using memset()
on data types larger than one byte may lead to unintended results unless the value is zero.
Return Value
The function returns the original pointer to the memory block that was set.
Examples for memset()
Example 1: Filling a Character Array with a Specific Character
This example demonstrates how to use memset()
to fill a character array with a specific character and properly terminate it as a C string.
Program
#include <stdio.h>
#include <string.h>
int main() {
char buffer[20];
// Fill the array with 'A'
memset(buffer, 'A', sizeof(buffer) - 1);
// Null terminate the string
buffer[19] = '\0';
printf("Filled character array: %s\n", buffer);
return 0;
}
Explanation:
- A character array
buffer
of size 20 is declared. memset()
fills the first 19 bytes of the array with the character ‘A’.- The last byte is manually set to
'\0'
to ensure the array is a proper null-terminated string. - The program prints the filled string.
Output:
Filled character array: AAAAAAAAAAAAAAAAAAA
Example 2: Zero-Initializing an Integer Array
This example shows how to use memset()
to zero-initialize an integer array. Since zero is represented by all zero bytes, the function is effective for initializing numeric arrays.
Program
#include <stdio.h>
#include <string.h>
int main() {
int numbers[5];
// Set all bytes of the array to 0
memset(numbers, 0, sizeof(numbers));
printf("Zero-initialized integer array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
Explanation:
- An integer array
numbers
of size 5 is declared. memset()
is used to set all bytes of the array to 0, effectively initializing every element to zero.- A loop prints the values of the array, confirming that all elements are zero.
Output:
Zero-initialized integer array: 0 0 0 0 0