C realloc() Function 🎯

beginner
17 min

C realloc() Function 🎯

Welcome to a comprehensive guide on the realloc() function in C programming! This function is a powerful tool for managing memory dynamically in your C programs. Let's dive in and explore its usage, purpose, and best practices. 📝

What is realloc()?

The realloc() function is used to change the size of a memory block that was previously allocated with malloc() or calloc(). This function can shrink or grow the allocated memory block and move it to a new location, if necessary.

c
void *realloc(void *ptr, size_t size);
  • ptr: A pointer to the memory block previously allocated with malloc(), calloc(), or realloc(). If ptr is NULL, realloc() behaves the same way as malloc().
  • size: The new size of the memory block in bytes.

Why use realloc()?

  • Memory Efficiency: By reallocating memory, you can avoid unnecessary memory leaks that may occur when resizing arrays or structs with fixed sizes.
  • Dynamic Memory Management: realloc() allows you to manage memory dynamically during program execution, making it essential for creating flexible and scalable applications.

How to use realloc()?

Let's walk through an example to see how to use realloc() in practice.

Example 1: Growing an array

c
#include <stdio.h> #include <stdlib.h> int main() { int *arr; int len = 0; // Allocate initial memory for an empty array arr = (int *)malloc(sizeof(int)); if (arr == NULL) { printf("Memory allocation failed!\n"); return 1; } // Add an initial value to the array arr[0] = 5; len++; // Double the size of the array when it's full while (len < 10) { if (len > 0) { arr = (int *)realloc(arr, len * sizeof(int)); if (arr == NULL) { printf("Memory reallocation failed!\n"); return 1; } } // Fill the new memory with values arr[len] = len * 2; len++; } // Print the contents of the array for (int i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0; }

In this example, we start by allocating an initial memory block for an empty array. As we add elements, we reallocate memory to double the size of the array when it becomes full. Finally, we print the contents of the array.

Example 2: Shrinking an array

c
#include <stdio.h> #include <stdlib.h> int main() { int *arr; int len = 10; // Allocate memory for an array of 10 integers arr = (int *)malloc(len * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed!\n"); return 1; } // Fill the array with values for (int i = 0; i < len; i++) { arr[i] = i * 2; } // Reduce the size of the array to 5 and reallocate memory arr = (int *)realloc(arr, 5 * sizeof(int)); // Print the remaining contents of the array for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } return 0; }

In this example, we first allocate memory for an array of 10 integers and fill it with values. Then, we reduce the size of the array to 5 and reallocate memory, effectively losing the remaining elements.

Pro Tip: Handling Memory Allocation Errors

Always check if memory allocation was successful by checking if the returned pointer is NULL. If so, handle the error gracefully, for example, by printing an error message and exiting the program.

Quiz

Quick Quiz
Question 1 of 1

Which C function is used to resize a memory block that was previously allocated with `malloc()` or `calloc()`?