C library functions -realloc()

C Standard Library - <stdlib.h>

realloc() is a function in the C standard library used to reallocate memory space. It is very important in dynamic memory management, especially when the size of allocated memory needs to be adjusted.

C Library Functionsvoid *realloc(void *ptr, size_t size)Attempt to readjust before callingmallocorcallocAllocatedptrThe size of the memory block pointed to.

Declaration

Below is the declaration of the realloc() function:

void *realloc(void *ptr, size_t size)

Parameter

  • ptr-- ptr points to a memory block to be reallocated, which was previously allocated by calling malloc, calloc, or realloc. If it is a null pointer, a new memory block will be allocated, and the function returns a pointer to it.
  • size-- The new size of the memory block, in bytes. If the size is 0 and ptr points to an existing memory block, the memory block pointed to by ptr is freed, and a null pointer is returned.

Return Value

  • If successful,realloc()Returns a pointer to the new memory block.
  • If it fails, returnNULL, and the original memory block remains unchanged (not freed).

Usage Instructions

  • realloc()It may move the memory block to a new location (if there is not enough space at the original location to accommodate the new size). If the move succeeds,ptrit will point to the new location. Special attention is needed: the oldptrThe pointer needs to be updated torealloc()the returned new address.
  • If memory allocation fails,realloc()returnNULL, and the original memory block is not freed. To avoid memory leaks, a temporary pointer should be used to receiverealloc()the return value, and check whether it isNULL。

Example

The following example demonstrates the usage of the realloc() function.

Example 1

#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str; /*Initial memory allocation*/ str = (char *) malloc(15); strcpy(str, "example"); printf("String = %s, Address = %p\n", str, str); /*Reallocate memory*/ str = (char *) realloc(str, 25); strcat(str, ".com"); printf("String = %s, Address = %p\n", str, str); free(str); return(0); }

Let us compile and run the above program, which will produce the following result:

String = example,  Address = 0x7fa2f8c02b10
String = example.com,  Address = 0x7fa2f8c02b10

Example 2

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = malloc(5 * sizeof(int));  // Allocate memory for 5 integers

    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Fill the array
    for (int i = 0; i < 5; i++) {
        arr[i] = i * 2;
    }

    // Reallocate memory to hold 10 integers
    int *new_arr = realloc(arr, 10 * sizeof(int));

    if (new_arr == NULL) {
        printf("Reallocation failed\n");
        free(arr);  // Free the original memory on failure
        return 1;
    }

    // Fill the new portion
    for (int i = 5; i < 10; i++) {
        new_arr[i] = i * 2;
    }

    // Print the new array
    for (int i = 0; i < 10; i++) {
        printf("%d ", new_arr[i]);
    }

    free(new_arr);  // Finally, free the memory
    return 0;
}

Notes

  • Check the return value: Always checkrealloc()the return value. If it returnsNULL, do not directly discard the original pointer.
  • Memory leak: ifrealloc()returnNULL, the original memory block will not be freed. At this point, the original memory should be freed and error handling should be performed.
  • Pointer invalidation: If you directly use the original pointer to receiverealloc()the returned new pointer, which may cause memory leaks, especially whenrealloc()it fails. Therefore, it is common to first use a temporary pointer to receive the return value.

Common uses

  • Dynamically expand the size of arrays or other data structures.
  • Used to handle variable-sized data sets at runtime, such as dynamically generated lists, strings, or caches, etc.

C Standard Library - <stdlib.h>

other extensions