memset
Function Usage
Populates a value into each byte of a memory block. It is usually used to initialize or clear the memory block.
Function Syntax
void *memset(void *ptr, int value, size_t num);
Parameters
Parameter |
Description |
Value Range |
Input/Output |
|---|---|---|---|
ptr |
Pointer to the destination memory used to store the reset data. |
Non-null pointer to a valid memory block, with at least num bytes accessible. |
Input/Output |
value |
Target value, which will be converted into the unsigned char type. |
0 to 255. The excess part will be truncated. |
Input |
num |
Number of bytes to be reset. |
Non-negative number that does not exceed the size of the memory block pointed to by ptr. |
Input |
Return Value
- Success: A pointer to the destination memory is returned. The return value is generally ignored.
- Failure: See those of open source glibc. No other exception values will be returned.
This function is used to initialize a memory block (by populating it with 0 or another value) or clear the block. As the ZVA instruction is used to optimize this operation, you should be aware of the system's ZVA block size.
The memset memory clearing operation supports only a DC ZVA block size of 64 bytes. To verify the block size, see ZVA Block Test.
ZVA Block Test
#include <stdio.h>
#include <stdint.h>
int main() {
uint64_t dczid;
// Use inline assembly to read dczid_el0.
asm volatile("mrs %0, dczid_el0" : "=r"(dczid));
if (dczid & 0x10) {
printf("DC ZVA not supported.\n");
} else {
uint32_t bs = dczid & 0xF;
uint32_t size = 1 << (bs + 2); // Block size = 2^(bs+2) bytes
printf("DC ZVA block size: %u bytes\n", size);
}
return 0;
}
Compile and execute the preceding content.
gcc test_zva.c -o test_zva ./test_zva
The command output is as follows:
DC ZVA block size: 64 bytes
Example
#include <stdio.h>
#include <string.h>
int main() {
char byteArr[10];
memset(byteArr, 'A', sizeof(byteArr));
for(int i = 0; i < sizeof(byteArr); i++) {
printf("%c ", byteArr[i]);
}
printf("\n");
return 0;
}
Output:
A A A A A A A A A A