Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Use of Realloc()
3.
Syntax of realloc()
4.
Example
4.1.
Example 1
4.2.
Example 2
5.
Frequently Asked Questions
5.1.
What is the return type of realloc() function?
5.2.
What will happen if the memory allocated is not dynamic?
5.3.
When does the relloc() function return NULL?
6.
Conclusion
Last Updated: Mar 27, 2024

Use of Realloc()

Author Shivam Sinha
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In C, calloc() or malloc() is used to allocate the blocks of memory space now; there may be a need to expand or shrink the memory according to one’s requirements, and this memory can be resized using the realloc() function which is a library function in C. So. we will see how we can use the realloc() function in C to resize the memory, we will also see a few examples to understand it.

Also See, Sum of Digits in C and C Static Function.

Use of Realloc()

Realloc() is a library function of C, which is included in the <stdlib.h> library. It stands for reallocation of memory which is used to change the size of the dynamically allocated memory; it resizes current memory blocks without changing the original content. One important point which should be considered is that reallocation is used in the case of dynamically allocated memory only, but if the memory allocated is not dynamic, then the behaviour is undefined. Here, dynamically allocated memory is the process of assigning the memory space during the execution time or the run time.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of realloc()

Syntax:

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

So, The function needs two arguments:

  • **(void *ptr): A pointer that points to the beginning of a memory block that we want to resize. 
  • (size_t size): This represents the new size of the block(in bytes), where size_t is just an alias of unsigned int, defined in the library of C. The new block can be smaller or larger than the original block.

 

Realloc deallocates the original object pointed to by ptr and returns a pointer to a new object. The contents of the new object are identical to that of the original object prior to deallocation. 

Example

Example 1

Let’s understand these with the help of an example:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *ptr = (int *)malloc(sizeof(int)*2);
    int i;
    int *ptr_new;
    
    *ptr = 10;
    *(ptr + 1) = 20;
    
    ptr_new = (int *)realloc(ptr, sizeof(int)*3);
    *(ptr_new + 2) = 30;
    for(i = 0; i < 3; i++){
        printf("%d ", *(ptr_new + i));
        
    }
    return 0;
}

Output: 

10 20 30

In this example, firstly, we want ptr to store the space of 2 integers, and then we store 10 and 20. Now we are deallocating the memory, and now we want to store the space of 3 integers, and then we store 30 in it. So it will simply print 10 20 30.

Also see,  Tribonacci Series and Short int in C Programming

Example 2

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


int main()
{
    int *p, i, n;


    printf("Initial size of the array is 4\n\n");
    p = (int*)calloc(4, sizeof(int));


    if(p==NULL)
    {
        printf("Memory allocation failed");
        exit(1); // exit the program
    }


    for(i = 0; i < 4; i++)
    {
        printf("Enter element at index %d: ", i);
        scanf("%d", p+i);
    }


    printf("\nIncreasing the size of the array by 3 elements ...\n ");


    p = (int*)realloc(p, 7 * sizeof(int));


    if(p==NULL)
    {
        printf("Memory allocation failed");
        exit(1); // exit the program
    }


    printf("\nEnter 3 more integers\n\n");


    for(i = 4; i < 7; i++)
    {
        printf("Enter element at index %d: ", i);
        scanf("%d", p+i);
    }


    printf("\nFinal array: \n\n");


    for(i = 0; i < 7; i++)
    {
        printf("%d ", *(p+i) );
    }



    return 0;
}

Output:

Original size of the array is 4


Enter element at index 0: 99
Enter element at index 1: 88
Enter element at index 2: 77
Enter element at index 3: 66


Increasing the size of the array by 3 elements ...


Enter 3 more integers


Enter element at index 4: 10
Enter element at index 5: 20
Enter element at index 6: 30


Final array:


99 88 77 66 10 20 30

In this example, initially, our array size is 4, so we can store up to 4 integers, and after that, we use the relloc() function to reallocate the memory keeping the original content same, so using relloc() function, our array size is 7, so we added 3 more integers. After that, we print all the elements stored in the array. 

You can also read about the dynamic arrays in c and Data Structure.

Frequently Asked Questions

What is the return type of realloc() function?

The return type of realloc() function is a void pointer.

What will happen if the memory allocated is not dynamic?

When a memory allocated is not dynamic, then the behaviour is undefined.

When does the relloc() function return NULL?

If there is not enough storage to expand the block to the given size, the original block is unchanged, and the realloc() function returns NULL.

Conclusion

In this article, we have discussed the use of realloc function.We also discussed its syntax with examples.

Enhance your skills in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and more with our Coding Ninjas Studio  Guided Path. If you want to sharpen your coding skills to the test, check out the mock test series and enter the contests on Coding Ninjas Studio! If you are just a beginner and want to know what questions big giants like Amazon, Microsoft, and Uber ask, check the problemsinterview experiences, and interview bundle for placement preparations.

You may consider our paid courses curated by experts to give your career an edge over others!

Do Upvote and Happy Learning!

Previous article
How does the free() method know the size of memory to be de-allocated?
Next article
Memory Leaks in C
Live masterclass