Reallocating Dynamic Arrays
Understand how to reallocate dynamic arrays in C effectively. Learn to manually allocate, copy, and free memory for resizing arrays and explore the use of the realloc function. Gain knowledge on safely managing memory pointers to prevent leaks and ensure proper dynamic memory handling.
We'll cover the following...
Introduction
We now know how to allocate dynamic arrays on the heap. We also know that we can size them, at runtime, according to the amount of data that needs to be stored. We no longer have to worry about running out of space!
However, what happens if at some point, after the allocation, we decide that we need more space?
The most obvious solution is to do the following steps:
- Allocate a new array of the required size.
- Copy the contents from the old array to the new array.
- Deallocate the old array.
Implementing everything from scratch
Let’s see how to implement these steps in the code. Assume we want to store all numbers from 0 to n inside an array.
In line 9, we allocate one array arr, which can hold five elements (INITIAL_SIZE). We then initialize all elements in ascending order, such that arr[i] = i (lines 16–19). We print this array ...