---
title: memset
description: "将指定值填充到内存区域的每个字节。通常用于初始化或清空内存区域。"
url: https://www.hikunpeng.com/document/detail/zh/kunpengboostkithistory/252RC1/accel/kunpengaccel_ksl_16_0210.html
sourcePath: /source/zh/kunpengboostkithistory/252RC1/accel/kunpengaccel_ksl_16_0210.html
indexId: 6de30ea0f30c9d4fa6fc506a587df5a6fd55e91bb2138598edc22fd11574037d76
---
# memset

#### 函数功能

将指定值填充到内存区域的每个字节。通常用于初始化或清空内存区域。


#### 函数定义

```
void *memset(void *ptr, int value, size_t num);
```


#### 参数说明

| 参数名 | 描述 | 取值范围 | 输入/输出 |
| --- | --- | --- | --- |
| ptr | 指向用于存储重置内容的目标内存指针。 | 非空指针，指向有效内存，至少有num字节可访问。 | 输入/输出 |
| value | 重置的目标值。 | 实际会被转换为unsigned char，有效范围为0~255（超过则截断） | 输入 |
| num | 被重置的字节数。 | 非负数，不超过ptr指向的内存大小。 | 输入 |


#### 返回值

- 成功：返回指向目标存储区内存的指针，返回值一般被忽略。
- 失败：对标开源Glibc，不返回特殊异常值。

主要用于初始化内存（如将内存设置为0或其他值）或清空数据。由于使用ZVA指令优化清零操作，因此需要注意系统ZVA块的大小。


对于memset内存清零操作，目前仅支持系统DC ZVA块大小为64B的场景，验证方法请参见ZVA块测试。

#### ZVA块测试

```
#include <stdio.h>
#include <stdint.h>
int main() {
uint64_t dczid;
// 使用内联汇编读取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);  // 块大小 = 2^(bs+2) 字节
printf("DC ZVA block size: %u bytes\n", size);
}
return 0;
}
```

编译并执行上述内容。

```
gcc test_zva.c -o test_zva
./test_zva
```

运行结果如下所示。

```
DC ZVA block size: 64 bytes
```


#### 示例

```
#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;
}
```

运行结果：

```
A A A A A A A A A A
```
