文档
注册
评分
提单
论坛
小智

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
搜索结果
找到“0”个结果

当前产品无相关内容

未找到相关内容,请尝试其他搜索词