Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Realloc C: Function & Syntax

Last Updated on March 2, 2023 by Prepbytes

In this article, we will discuss the realloc function in c with examples,realloc syntax in c, parameters of realloc, the uses of realloc c, and the advantages, and limitations of the realloc function in c.

What is Realloc in C?

‘realloc’ is a function in C that changes the size of a previously allocated block of memory. It takes a pointer to the previously allocated memory as its first argument and the new size as its second argument. If the new size is larger than the original size, the additional memory is uninitialized. If the new size is smaller than the original size, the memory block is truncated. If the function is successful, it returns a pointer to the newly allocated memory block. If the function fails, it returns a null pointer.

The pointer returned by realloc might be different from the pointer passed as the first argument, so the programmer needs to be prepared to update any existing pointers that point to the old block of memory.

It’s important to note that the memory allocated by realloc is not guaranteed to be contiguous with the memory previously allocated and that any data stored in the reallocated memory block may be lost if the memory block is moved.

It’s also important to check if the realloc call was successful and to free the memory after it is no longer needed to avoid memory leaks.

Realloc Syntax in C

The syntax for the realloc() function in C is as follows:

ptr = realloc (ptr,new_size);

Here is an example of using realloc() to resize a previously allocated memory block:

Code Implementation of Realloc in C

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

int main() {
    // Allocate memory for 10 integers
    int *ptr = (int *) malloc(10 * sizeof(int));
    ptr[0] = 1;
    ptr[1] = 2;
    ptr[2] = 3;
    ptr[3] = 4;
    ptr[4] = 5;
    ptr[5] = 6;
    ptr[6] = 7;
    ptr[7] = 8;
    ptr[8] = 9;
    ptr[9] = 10;

    // Reallocate memory for 15 integers
    ptr = (int *) realloc(ptr, 15 * sizeof(int));
    
    for (int i = 9; i < 15; i++) {
        ptr[i] = i + 1;
    }
    for (int i = 0; i < 15; i++)
        printf("%d ", ptr[i]);
    free(ptr);
    return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 

Points to Note:

  1. In C you have to cast the return of malloc and realloc to the desired pointer type.
  2. You should always check whether the realloc() call was successful, by checking if it returned a null pointer, before using the new memory block to avoid undefined behavior.
  3. It is important to free the memory block after it is no longer needed to avoid memory leaks.

Parameters of Realloc C

The realloc() method in C accepts two inputs. The parameters are given below:

  1. Ptr: A pointer to the memory block that must be resized. It is the pointer returned by a previous malloc(), calloc(), or realloc(). If ptr is null, realloc() acts similarly to malloc().
  2. size: size is an unsigned integer that specifies the new size of the memory block, in bytes. If the size is zero, realloc() frees the memory pointed to by ptr and returns a null pointer.

The realloc() function attempts to resize the memory block pointed to by ptr to the new size specified by size. If successful, the function returns a pointer to the newly resized memory block. If the function fails to resize the memory block, it returns a null pointer, and the original memory block is not modified.

It’s important to note that realloc() may move the memory block to a different location in memory, so any pointers to the old memory block will become invalid. It’s also important to check for errors and handle them appropriately because realloc() might not be able to allocate the requested amount of memory.

Return Value of Realloc Function in C

The realloc() function in C returns a pointer to the newly allocated memory block. The new memory block will have the same contents as the original memory block, and any additional memory will be set to zero.

The pointer returned by realloc() may be different from the pointer passed as the first argument, so it is important to update any pointers that point to the original memory block. If the memory cannot be resized, realloc() will return a null pointer and the original memory block will be unchanged.

If the realloc() function is successful, it will return a pointer to the newly allocated memory block. If the function fails to resize the memory, it will return a null pointer and the original memory block will be unchanged.

For example,

#include 
#include 

int main() {
    int* arr = (int*) malloc(10 * sizeof(int));

    int* new_arr = (int*) realloc(arr, 20 * sizeof(int));
    if (new_arr == NULL) {
        printf("realloc failed");
    }
    else {
        arr = new_arr;
    }

    free(arr);
    return 0;
}

In the above example, the realloc() function is called to resize the memory block. It checks whether the returned pointer is NULL or not. If it is NULL, the realloc function failed, else it updates the original pointer with the returned pointer.

Uses of Realloc Function in C

The realloc() function in C can be useful in a few different situations:

  • Resizing arrays: One of the main uses of realloc() is to change the size of an array that has been previously allocated on the heap. This can be useful when the program needs to store more data than was originally allocated, or when the program no longer needs as much data as was originally allocated.
  • Dynamic memory management: realloc() can be used in conjunction with malloc() to manage memory dynamically. This can be useful when the program needs to allocate memory at runtime and the size of the memory needed is not known at compile time.
  • Reducing memory fragmentation: If a program frequently calls realloc() to change the size of memory blocks, it can lead to memory fragmentation, where there are many small, unused blocks of memory scattered throughout the heap. realloc() can be used to reduce fragmentation by consolidating small blocks of memory into larger blocks.
  • Memory optimization: realloc() can be used to optimize memory usage by allocating memory only when it is needed and freeing it when it is no longer needed. This can be useful for programs that need to run for long periods of time or on systems with limited memory.
  • Creating dynamic data structures: realloc() can be used to create dynamic data structures like linked lists and trees, where the number of nodes in the structure can change at runtime.
  • Expanding a buffer: realloc() is commonly used to expand a buffer to hold more data, for example when reading data from a file.

It’s important to note that realloc() should be used with care, and it’s important to understand the trade-offs involved in using it. It’s also important to check for errors and handle them appropriately.

Examples of Realloc in C

Here are a few examples of how the realloc() function in C can be used:

  1. Resizing an array:

    Code Implementation:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        char* arr = (char*) malloc(10 * sizeof(char));
        for (int i = 0; i < 10; i++) {
            arr[i] = 65 + i;
        }
    
        arr = (char*) realloc(arr, 15 * sizeof(char));
        for (int i = 10; i < 15; i++) {
            arr[i] = 65 + i;
        }
    
        for (int i = 0; i < 16; i++) {
            printf("%c ", arr[i]);
        }
    
        free(arr);
        return 0;
    }

    Output:

    A B C D E F G H I J K L M N O

    This code creates an array of 10 characters on the heap using malloc() and assigns first 10 alphabets to their respective indices. Then it uses realloc() to resize the array to 15 characters and assigns new characters.

  2. Creating a dynamic buffer

    Code Implementation:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
        char* buffer = (char*) malloc(6 * sizeof(char));
        strcpy(buffer, "Prep ");
    
        buffer = (char*) realloc(buffer, 15 * sizeof(char));
        strcat(buffer, "Bytes!!");
    
        printf("%s\n", buffer);
    
        free(buffer);
        return 0;
    }

    Output:

    Prep Bytes!!

    This code creates a buffer of 6 characters on the heap using malloc(), copies "Prep " into it, and then reallocates to 15 characters and appends "Bytes!!" to the buffer.

Advantages of using Realloc

There are a few advantages of using realloc() in c:

  • Memory Efficiency: realloc() allows for more efficient use of memory by allowing for resizing of allocated memory blocks, rather than having to allocate new blocks and copy data over. This can help to reduce fragmentation and improve overall performance.
  • Dynamic Memory Allocation: realloc() enables dynamic memory allocation, which means that the size of the memory block can be changed at runtime. This is particularly useful in situations where the amount of memory required is not known in advance.
  • Reduced Code Complexity: Using realloc() to resize memory blocks can simplify the process of managing dynamic memory allocation in a program, as it eliminates the need to keep track of multiple memory blocks and manually copy data between them.
  • Flexibility: realloc() allows for more flexibility in the design of a program, as it can be used to dynamically allocate and resize memory as needed, rather than having to pre-allocate a fixed amount of memory.
  • Better memory management: By using realloc() to resize memory blocks, you can reduce the amount of memory wasted due to over-allocation, and increase the amount of memory available for other parts of the program.

Limitations of Using Realloc

There are a few limitations of using realloc() in c:

  • Realloc C can be inefficient: The realloc() function needs to copy the old data from the original memory block to the new memory block, which can take a significant amount of time for large arrays.
  • Realloc C can be unreliable: realloc() might not be able to allocate the requested amount of memory, in which case it returns a null pointer. The programmer needs to check for this and handle the error appropriately.
  • Realloc C can move the memory block: When realloc() is called, the memory block might need to be moved to a different location in memory. This can cause pointers to the memory block to become invalid, so the programmer needs to be prepared to update any existing pointers that point to the old memory block.
  • Realloc C can lead to fragmentation: If the program frequently calls realloc() to change the size of memory blocks, it can lead to memory fragmentation, where there are many small, unused blocks of memory scattered throughout the heap. This can make it difficult to allocate large blocks of memory.
  • Realloc C can cause memory leaks: If the program calls realloc() and then fails to update the pointers to the new memory block or to free the old memory block, it can cause memory leaks, where blocks of memory are no longer accessible but cannot be freed.
  • Realloc C can be slower than allocating new memory and copying the data over if you know the size of the array you are going to use, it’s more efficient to allocate the appropriate amount of memory in the first place and use memcpy to copy the data over.

It’s important to note that realloc() can be useful in some cases, but it should be used with care, and it’s important to understand the trade-offs involved in using it.

Summary
In this article, we looked at the C programming language’s realloc() method. The article leads us to the following points:

  • realloc() function in C.
  • The realloc() syntax in C.
  • Parameters of realloc().
  • The result of the realloc() C function.
  • Realloc() C function uses.
  • Examples of how the realloc() C method works.
  • Advantages of realloc() C function.
  • Disadvantages of realloc() C function.

Leave a Reply

Your email address will not be published. Required fields are marked *