---
title: realloc
description: "内存重新分配并将旧内存中数据拷贝至新内存中。"
url: https://www.hikunpeng.com/document/detail/zh/kunpengboostkithistory/251RC1/accel/kunpengaccel_ksl_16_0022.html
sourcePath: /source/zh/kunpengboostkithistory/251RC1/accel/kunpengaccel_ksl_16_0022.html
indexId: 07ae40f97cbb175802f60ee8f4ed12f36bc94731afa2a5e16fce122e67aa640476
---
# 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;
}
```

编译。

```
gcc run_your_application.c -o run_your_application -I/usr/local/ksl/include -L/usr/local/ksl/lib
```

运行。

```
LD_PRELOAD=/usr/local/ksl/lib/libkqmalloc.so ./run_your_application
```

运行结果：

```
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
```
