realloc
Reallocate memory and copy data in the old memory to the new memory.
void *realloc(void *old_pointer, size_t new_size);
Parameters
Parameter |
Description |
Value Range |
Input/Output |
|---|---|---|---|
old_pointer |
Pointer to the old memory to be reallocated. |
The value cannot be NULL. |
Input |
new_size |
Number of bytes of the reallocated memory. |
The value cannot be negative. |
Input |
Return Value
- Success: A pointer to the reallocated memory is returned.
- Failure: A null pointer is returned.
Example
#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;
}
Output:
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
Parent topic: Function Syntax