realloc in C Programming

realloc()

With the function realloc, you can change the size of the allocated area once. Has the following form:

void * realloc (void * ptr, size_t size);

The first argument specifies the address of an area that is currently allocated to the size in bytes of the modified second argument. Change the size, the return value is returned in re-allocated address space. Otherwise, it returns NULL.

Size may be smaller but larger than the original. If you have small, reduced what was written in part will be inaccessible. If you increase the portion of the region will remain an indefinite increase.

The address of the source address changed, but the same could possibly be different, even if the different areas of the old style, because it is automatically released in the function realloc, for the older areas it is not necessary to call the free function. However, if the function fails and returns NULL, realloc, the older area is to remain still valid. Therefore, the first pointer argument of the function realloc, both can be NULL pointer return value is not returned.

#include <stdio.h>
#include <stdlib.h>
  
int main(void) {
    int *p1, *p2;
    p1 = (int *)calloc(5, sizeof(int)); /* Allocate space for an array of 5 integers */

    /* Do something */

    p2 = (int *)realloc(p1, sizeof(int)); /* Reallocate space for one integer */
    if (p2 == NULL) { /* Check if reallocation was successful */
        free(p1); /* If reallocation fails, free the original memory region */
        return 0;
    }
    p1 = NULL; /* Safety measure: Set p1 to NULL since realloc() frees the original memory */

    /* Do something */

    free(p2);
    return 0;
}

The `realloc` function is a versatile function with various capabilities. However, it's essential to understand its nuances, pros, and cons for effective use.

For instance, if a NULL pointer is passed as the first argument to `realloc`, it behaves similarly to calling `malloc` with the size specified in the second argument. Similarly, if the second argument is zero, it operates similarly to `free`, deallocating the space pointed to by the pointer passed as the first argument.

In essence, the behavior of `realloc` depends on its arguments, and it's crucial to interpret the result correctly, which might not always indicate an error. However, certain scenarios can lead to undefined behavior. For example, consider the common usage:

char *p2 = realloc(p1, size);

If the variable `size` is zero, this doesn't behave the same as calling `free`. Similarly, if `p1` is NULL, it behaves like `malloc`. The behavior when both arguments are NULL and 0 respectively is undefined.

Furthermore, the pointer passed as the first argument to `realloc` must point to a valid memory area allocated using one of the functions `malloc`, `calloc`, or `realloc`. If it's a NULL pointer, it's equivalent to calling `malloc`.

Because of its complexity, here's a simplified implementation of the `realloc` function to aid understanding:

void *realloc(void *ptr, size_t size) {
    if (ptr == NULL) {
        // If ptr is NULL, behave like malloc
        return malloc(size);
    }
    if (size == 0) {
        // If size is zero, behave like free and return NULL
        free(ptr);
        return NULL;
    }
    
    // Actual realloc implementation here
}

This simplified version outlines the basic behavior of `realloc` and can aid in understanding its functionality.

void *realloc(void *ptr, size_t size) {
    char *p;

    if (ptr == NULL) {
        // If the pointer is NULL, behave like malloc
        return malloc(size);
    }
    if (size == 0) {
        // If size is zero, behave like free and return NULL
        free(ptr);
        return NULL;
    }

    p = malloc(size); // Allocate a new block of memory of the requested size
    if (p == NULL) {
        return NULL; // Return NULL if malloc fails to allocate memory
    }

    // Copy data from the old memory block to the new one
    // We assume that the old block is smaller or equal in size to the new one
    memcpy(p, ptr, size);
    free(ptr); // Free the old memory block
    return p; // Return a pointer to the newly allocated memory block
}

This version correctly implements the realloc function to resize a memory block pointed to by ptr. If ptr is NULL, it behaves like malloc and allocates a new memory block of the specified size. If size is zero, it behaves like free, releasing the memory block pointed to by ptr. Otherwise, it allocates a new memory block of the requested size, copies the data from the old block to the new one, frees the old block, and returns a pointer to the new block.

Here are the points you need to remember.

  • The contents of the object will remain unaltered up to the lesser of the new and old sizes.
  • If the new size of the memory object would require movement of the object, the space for the previous instantiation of the object is freed.
  • If the new size is larger, the contents of the newly allocated portion of the object are unspecified.
  • If size is zero and ptr isn't a null pointer, the object pointed to is freed.
  • If the space can't be allocated, the object remains unaltered.
  • If ptr is a null pointer, realloc() acts like malloc() for the specified size.

Here's an example ,learn this example and then try applying the same idea to write your own programs.

Ready to get started?

Ready to embark on your journey into the world of C programming? Our comprehensive course provides the perfect starting point for learners of all levels. With engaging lessons, hands-on exercises, and expert guidance, you'll gain the skills and confidence needed to excel in this fundamental programming language. Let's dive in and unlock the endless possibilities of C programming together!