How to resize allocated block of memory using realloc function in C

C Dynamic Memory Reallocation

In C programming, dynamic memory reallocation is a way for programs to expand or shrink a previously allocated block of memory.

It is useful in situations where you need to change the size of an array or other data structure at runtime.

realloc() Functions for Dynamic Memory Reallocation

The C standard library provides realloc() function to reallocate dynamic memory in the <stdlib.h> header file.

The realloc() function in C is used to resize a previously allocated block of memory using malloc() or calloc() functions.

It is used to expand or shrink the memory block without losing the minimum existing data.

It is also very crucial to check whether the realloc() function allocates the requested memory. Otherwise it will lead to undefined behavior and your program may crash.

Syntax of realloc() Function

*ptr: A pointer to the memory block that you want to resize. This pointer must have been previously returned by malloc(), calloc(), or realloc() function.

size: The number of bytes to allocate for the block of memory

Example of realloc() Function

Explanation of code:

  • int *ptr = (int *)malloc(3 * sizeof(int));: This line allocates memory for 3 interger numbers.
  • if (ptr == NULL): This is a crucial error checking. If malloc() function fails to allocate the requested memory due to some reasons, it will return NULL.
  • ptr[0] = 5;...ptr[2] = 9;: These lines assign values to the elements of the dynamically allocated array.
  • ptr = realloc(ptr, 5 * sizeof(int));: This line resizes the memory to hold 5 integers.
  • for (int i = 0; i < 5; i++){...}: This loop iterates over the array and prints each element.
  • free(ptr);: The free() function deallocates the memory previously allocated by realloc(). The free() function takes the pointer ptr as argument.

The free() function is crucial in dynamic memory management process because it deallocates the memory that was previously allocated dynamically. By deallocating memory with free() function, it is ensured that the program uses memory efficiently. In severe cases, memory leaks can exhaust the available memory resources, leading to system instability and crashes.

Live Code Playground

In the following C code editor, you can practice by resizing allocated memory blocks using realloc() function. Click the 'Execute' button to execute the code; the executed output will be displayed in the following C Code Output frame. Practice until you become comfortable and proficient with your code.

C logo C Online Editor
C Code Output