---
title: realloc
description: "内存重新分配并将旧内存中数据拷贝至新内存中。"
url: https://www.hikunpeng.com/document/detail/zh/kunpengboostkithistory/2300/accel/kunpengaccel_ksl_16_0022.html
sourcePath: /source/zh/kunpengboostkithistory/2300/accel/kunpengaccel_ksl_16_0022.html
indexId: 70470e0659bc80f2ce4d093239a839b0b4b29387ecba00369e7a7f471fdba8d174
---
# realloc

内存重新分配并将旧内存中数据拷贝至新内存中。

void *realloc(void *old_pointer, size_t new_size);

#### 参数

| 参数名 | 描述 | 取值范围 | 输入/输出 |
| --- | --- | --- | --- |
| old\_pointer | 指向需重新分配的旧内存指针。 | 非空 | 输入 |
| new\_size | 重新申请内存的字节数。 | 非负数 | 输入 |


#### 返回值

- 成功：返回指向新分配内存的指针。
- 失败：返回空指针。


#### 示例

```
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "kqmalloc.h"
#define KQMALLOC_TEST_LEN 10
void ReallocExample()
{
int8_t *old_pointer = (int8_t *)malloc(KQMALLOC_TEST_LEN * sizeof(int8_t));
if (old_pointer == NULL) {
printf("old_pointer is null\n");
return;
} else {
printf("old_pointer address: %lx\n", old_pointer);
for (int8_t i = 0; i < KQMALLOC_TEST_LEN; ++i) {
old_pointer[i] = i;
}
printf("old_pointer test data:");
for (int8_t i = 0; i < KQMALLOC_TEST_LEN; ++i) {
printf(" %d", old_pointer[i]);
}
printf("\n");
}
int8_t *new_pointer = (int8_t *)realloc(old_pointer, 2 * KQMALLOC_TEST_LEN * sizeof(int8_t));
if (new_pointer == NULL) {
printf("new_pointer is null\n");
free(old_pointer);
return;
} else {
printf("new_pointer address: %lx\n", new_pointer);
printf("new_pointer test data:");
for (int8_t i = 0; i < KQMALLOC_TEST_LEN; ++i) {
printf(" %d", new_pointer[i]);
}
printf("\n");
}
free(old_pointer);
free(new_pointer);
}
int main(void) {
ReallocExample();
return 0;
}
```

运行结果：

```
old_pointer address: ffff921c8174
old_pointer test data: 0 1 2 3 4 5 6 7 8 9
new_pointer address: ffff921c87ec
new_pointer test data: 0 1 2 3 4 5 6 7 8 9
```
