Reallocating Dynamic Arrays

Learn to reallocate the heap memory of arrays.

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 in lines 22–27.

Then, we decide that we no longer want all the numbers from 0 to 5, but we want all the numbers from 0 to 9. The original arr can not hold 10 numbers, so we need to allocate new memory.

We begin the reallocation process:

  • Allocate a new array big enough to hold the new data. We do it in line 29.
  • We copy the data from the old array to the new array. We use the memcpy function, in line 35.
    memcpy(dest, source, num_bytes) copies num_bytes of data from source to dest. Alternatively, we could have written a for loop and copied the elements manually.
  • We free the old array in line 36.

Lastly, we have to fill the rest of the new array with the new data, the number from 5 to 9. We do this in lines 39–42.

After we’re done with the new array newArr, we have to deallocate it (line 52).

Get hands-on with 1200+ tech skills courses.