C programming stdlib.h function - void *realloc(void *ptr, size_t size)

The realloc function is a memory allocation function in the C standard library that is used to resize a block of memory that was previously allocated using malloc, calloc, or realloc. The syntax of the realloc function is as follows:

void *realloc(void *ptr, size_t size);
Source‮.www:‬theitroad.com

The ptr argument is a pointer to the memory block to be resized. If ptr is a null pointer, the realloc function behaves the same as the malloc function.

The size argument is the new size of the memory block, in bytes.

The realloc function returns a pointer to the first byte of the resized memory block. If the function is unable to allocate the requested amount of memory, it returns a null pointer.

Here is an example that demonstrates how to use the realloc function:

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

int main(void) {
    int *ptr = (int *)malloc(10 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < 10; i++) {
        ptr[i] = i;
    }

    int *new_ptr = (int *)realloc(ptr, 20 * sizeof(int));
    if (new_ptr == NULL) {
        printf("Memory allocation failed\n");
        free(ptr);
        return 1;
    }

    for (int i = 10; i < 20; i++) {
        new_ptr[i] = i;
    }

    for (int i = 0; i < 20; i++) {
        printf("%d ", new_ptr[i]);
    }
    printf("\n");

    free(new_ptr);
    return 0;
}

In this example, the malloc function is used to allocate memory for an array of 10 int elements. The size of each element is sizeof(int). The program then uses a for loop to fill the array with values. The realloc function is then used to resize the memory block to hold 20 int elements. If the realloc function is successful, it returns a new pointer to the resized memory block. The program then fills the new elements with values and prints out all 20 elements of the array. Finally, the free function is called to deallocate the memory block pointed to by new_ptr. Note that if the realloc function returns a null pointer, the original memory block pointed to by ptr is not automatically deallocated, so it must be freed explicitly using the free function.