C realloc() Deep Dive 🎯

beginner
20 min

C realloc() Deep Dive 🎯

Welcome to our deep dive into the realloc() function in C programming! In this lesson, we'll explore the realloc() function, its purpose, and how to use it effectively. By the end of this lesson, you'll be able to manage dynamic memory allocation like a pro! 💡

What is realloc()? 📝

In C programming, realloc() is a library function that changes the size of an array or a dynamically allocated memory block and moves it, if necessary, to a new location.

When to use realloc()? 📝

  • When you need to grow or shrink an existing block of memory
  • When you've allocated more memory than you need, and now you want to use the remaining space
  • To optimize memory usage when you know the exact size you need at runtime

Syntax 📝

c
void *realloc(void *ptr, size_t size);
  • ptr: the pointer to the memory block you want to resize
  • size: the new size of the memory block

Example 1: Growing an Array 💡

c
#include <stdio.h> #include <stdlib.h> int main() { int *arr, i; int arr_size = 5; // Allocate memory for an array of size 5 arr = (int *)malloc(arr_size * sizeof(int)); // Fill the array for(i = 0; i < arr_size; i++) arr[i] = i * i; // Check if the array is filled correctly for(i = 0; i < arr_size; i++) printf("arr[%d] = %d\n", i, arr[i]); // Increase the array size by 2 arr_size += 2; // Reallocate memory for the larger array arr = (int *)realloc(arr, arr_size * sizeof(int)); // Fill the newly allocated elements for(; i < arr_size; i++) arr[i] = i * i; // Check if the array is filled correctly for(i = 0; i < arr_size; i++) printf("arr[%d] = %d\n", i, arr[i]); return 0; }

Example 2: Shrinking an Array 💡

c
#include <stdio.h> #include <stdlib.h> int main() { int *arr, i; int arr_size = 10; // Allocate memory for an array of size 10 arr = (int *)malloc(arr_size * sizeof(int)); // Fill the array for(i = 0; i < arr_size; i++) arr[i] = i * i; // Check if the array is filled correctly for(i = 0; i < arr_size; i++) printf("arr[%d] = %d\n", i, arr[i]); // Decrease the array size to 5 arr_size = 5; // Reallocate memory for the smaller array arr = (int *)realloc(arr, arr_size * sizeof(int)); // Check if the array is correctly resized printf("After reallocating, the size is: %ld\n", sizeof(arr) / sizeof(int)); return 0; }

Quiz 💡

Quick Quiz
Question 1 of 1

What is the purpose of the `realloc()` function in C programming?


That's it for our deep dive into the realloc() function in C programming! With a good understanding of dynamic memory management and the realloc() function, you can now create more efficient and robust C programs. Happy coding! 💡