Understanding realloc() function in C

Understanding realloc() function in C

02 May 2024
Beginner
224 Views
12 min read
Learn via Video Course & by Doing Hands-on Labs

C Programming For Beginners Free Course

The realloc() in C: An Overview

The realloc()  function de-allocates the old object pointed to by pointer (ptr) and returns a pointer to a new object that has the size specified by size. The contents of the new object are similar to that of the old object leading to deallocation, up to the lesser of the new and old sizes. 

In this C Tutorial, we will explore more about the realloc() function in C Programming which will include what is the realloc() function in C, the syntax of the realloc() function in C, realloc() function with its example. 

What is the realloc() function in C?

  • The "realloc" is a standard library function in C.
  • It is mainly used to resize dynamically allocated memory blocks.
  • It has two arguments, a pointer to a previously allocated memory block and the new size to which the memory block needs to be resized.

Syntax :

The following is the syntax of realloc() function:

 ptr = realloc (ptr,new_size);  

Parameters of realloc() Function in C

The realloc() method has two inputs. They are as follows:

1.ptr

  • It is nothing but a pointer to the memory block which has to be resized.
  • The ptr parameter is the pointer returned by a previous malloc() function, calloc() function, or realloc() function.
  • If suppose this parameter is null, realloc() acts like a malloc() function.

2.size:

  • This parameter is an unsigned integer that indicates the new size of the memory block.
  • The size parameter is in bytes structure.
  • The realloc() function frees the memory pointed to by ptr and returns a null pointer if the size is zero.

Parameters of Realloc() Function in C

Code Implementation of realloc in C

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

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

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

Output


1 2 3 4 5 6 7 8 9 10
    

realloc() Function with Dynamic stack

Let's elaborate the realloc() function in the C Compiler.
#
#include   
#include   
typedef struct {  
    int* arr;  
    int top;  
    int size;  
} Stack;  
Stack* create_stack(int size) {  
    Stack* stack = (Stack*)malloc(sizeof(Stack));  
    if (stack == NULL) {  
printf("Failed to allocate memory\n");  
        return NULL;  
    }  
    stack->arr = (int*)malloc(size * sizeof(int));  
    if (stack->arr == NULL) {  
printf("Failed to allocate memory\n");  
        free(stack);  
        return NULL;  
    }  
    stack->top = -1;  
    stack->size = size;  
    return stack;  
}  
void push(Stack* stack, int x) {  
    if (stack->top == stack->size - 1) {  
        // stack is full, resize it  
        int new_size = 2 * stack->size;  
        int* new_arr = (int*)realloc(stack->arr, new_size * sizeof(int));  
        if (new_arr == NULL) {  
printf("Failed to reallocate memory\n");  
            return;  
        }  
        stack->arr = new_arr;  
        stack->size = new_size;  
    }  
    stack->top++;  
    stack->arr[stack->top] = x;  
}  
int pop(Stack* stack) {  
    if (stack->top == -1) {  
printf("Stack is empty\n");  
        return -1;  
    }  
    int x = stack->arr[stack->top];  
    stack->top--;  
    return x;  
}  
  
void free_stack(Stack* stack) {  
    free(stack->arr);  
    free(stack);  
}  
int main() {  
    Stack* stack = create_stack(3);  
    if (stack == NULL) {  
        return 1;  
    }  
push(stack, 4);  
push(stack, 5);  
push(stack, 6);  
push(stack, 7);  
push(stack, 8);  
  
printf("%d\n", pop(stack));  
printf("%d\n", pop(stack));  
printf("%d\n", pop(stack));  
printf("%d\n", pop(stack));  
printf("%d\n", pop(stack));  
free_stack(stack);  
    return 0;  
}  

Output

8
7
6
5
4    

Uses of realloc() Function in C

  • Array Resizing: It is mainly used to change the size of an array that is previously allocated on the heap and it will be useful in the case when the program needs to store more data than was originally allocated.
  • Dynamic memory: This function is used in conjunction with malloc() to manage memory dynamically.
  • Optimizing Memory allocation: It is used to optimize memory usage by allocating memory only when it is needed.
  • Dynamic data structures: It can be used to create dynamic data structures such as linked lists and trees, where the number of nodes in the structure can change at runtime.

Advantages of realloc() function

  • Efficient Memory usage: This function allows more efficient use of memory by resizing allocated memory blocks. So it reduces fragmentation and improves overall performance.
  • Low Complexity: Using this function to resize memory blocks it can simplify the process of managing dynamic memory allocation because it eliminates the need to keep track of multiple memory blocks and also manually copy data between them.
  • Flexibility: The function allows for more flexibility in the design of a code, and it can be used to dynamically allocate and resize memory.

Disadvantages of realloc() function

  • Fragmentation: If the program frequently calls realloc() function to change the size of memory blocks, it can lead to memory fragmentation.
  • Memory leaks: If the code calls this function and then fails to update the pointers to the new memory block or to free the old memory block, it will cause memory leaks.
  • Slower Process: It allocates new memory and copies the data over if you know the size of the array we 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.
Conclusion:
So, we have learned about the realloc() function in C. I hope you enjoyed learning these concepts while programming with C. Feel free to ask any questions from your side. Your valuable feedback or comments about this article are always welcome. To learn C Programming from scratch, enroll in our C Programming Certification Course and get the best guide to learn C step by step with real-time examples.

FAQs

Q1. What is realloc and free function?

The realloc() function is used to resize the dynamically allocated memory and free() is used to deallocate a memory block. 

Q2. Can we use realloc without malloc?

Yes.malloc is not required in each case , you can use realloc only.

Q3. Why is realloc function used?

It is used to resize the memory block pointed to a pointer that was previously allocated to the variable by the malloc() or calloc() function.
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Full Stack .Net Certification Training May 26 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification Training May 26 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training May 26 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Azure DevOps Certification Training Course Jun 01 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Data Structures and Algorithms Training Jun 04 TUE, FRI
Filling Fast
08:30PM to 10:00PM (IST)
Get Details
ASP.NET Core Certification Training Jun 14 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
ASP.NET Core (Project) Jun 22 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this