realloc
Function Usage
Reallocates memory and copies data in the old memory to the new memory.
Function Syntax
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #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:
1 2 3 4 | 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