REW

How Can You Increase The Size Of A Dynamically Allocated Array?

Published Aug 29, 2025 5 min read
On this page

A dynamically allocated array cannot be resized directly, as the underlying memory block has a fixed size after its initial allocation.

Instead, you must allocate a new, larger block of memory, copy the elements from the old array to the new one, and then free the memory used by the original array. This process can be implemented manually or, more efficiently and safely, by using a built-in library feature.

Method 1: The manual copy-and-reallocate method

This approach involves several manual steps and is fundamental to understanding how dynamic arrays work under the hood. While error-prone and not recommended for typical C++ applications, it is a key programming concept.

Steps for manually resizing a C++ dynamic array:

  1. Allocate a new, larger array on the heap using new[]. This new array must have a larger size than the original.
  2. Copy the data from the old array to the new one. This is typically done with a for loop or a memory-efficient function like std::copy or memcpy.
  3. Delete the old array to prevent memory leaks. You must use delete[] to deallocate the memory correctly.
  4. Point the original array's pointer to the new array. This makes the newly allocated memory accessible through the original variable name.

Example in C++:

int main() {
    int old_size = 5;
    int* p_old = new int[old_size]; // Allocate original array
    for (int i = 0; i < old_size; ++i) {
        p_old[i] = i; // Initialize elements
    }
    int new_size = 10;
    int* p_new = new int[new_size]; // Allocate new, larger array
    // Copy elements from the old array to the new one
    for (int i = 0; i < old_size; ++i) {
        p_new[i] = p_old[i];
    }
    delete[] p_old; // Delete the old array
    p_old = p_new; // Point the old pointer to the new array
    p_new = nullptr; // Nullify the temporary pointer
    // Use the resized array (p_old now points to the new, larger memory)
    for (int i = 0; i < old_size; ++i) {
        std::cout << p_old[i] << " ";
    }
    std::cout << std::endl;
    delete[] p_old; // Clean up the final array
    return 0;
}

Use code with caution.

Method 2: Use std::vector in C++

For modern C++ development, the Standard Template Library (STL) std::vector class is the correct and safest way to handle resizable arrays. A std::vector is a class that encapsulates the manual copy-and-reallocate logic, along with many other useful features, into a robust, easy-to-use container.

Benefits of using std::vector:

  • Automatic memory management:std::vector handles all memory allocation, deallocation, and resizing internally. It uses smart reallocation strategies to avoid the performance overhead of frequent copying.
  • Safety: The class automatically manages resource cleanup, preventing memory leaks, and handles exceptions correctly.
  • Rich functionality: It provides a rich set of methods, such as push_back(), pop_back(), resize(), and at(), for manipulating its contents.
  • Capacity optimization:std::vector often allocates more memory than immediately needed, so subsequent additions can happen quickly without triggering a resize operation.

Example using std::vector:

#include <iostream>
#include <vector>
int main() {
    std::vector<int> numbers; // Create a vector (dynamic array)
    // Add elements, the vector will automatically resize as needed
    numbers.push_back(10);
    numbers.push_back(20);
    numbers.push_back(30);
    // Increase the size of the vector to 5. New elements are value-initialized (to 0).
    numbers.resize(5);
    // Print the elements of the resized vector
    for (int i : numbers) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
    return 0;
}

Use code with caution.

Method 3: Use realloc() in C

In the C programming language, the realloc() function is the standard way to resize a block of dynamically allocated memory. It attempts to resize the existing memory block. If it succeeds, it may return the same pointer. If not, it allocates a new, larger block, copies the old data, frees the old block, and returns a pointer to the new block.

Important considerations for realloc():

  • realloc() only works on memory allocated by malloc(), calloc(), or a previous realloc() call.
  • It does not guarantee that the reallocated memory will occupy the same address. You must always use the return value of realloc() to ensure you are referencing the correct memory.
  • It copies raw bytes, so it should not be used for C++ objects with complex constructors or destructors.
  • If realloc() fails to allocate the requested memory, it returns a null pointer and the original memory block remains unchanged and is not deallocated.

Example in C:

#include <stdio.h>
#include <stdlib.h>
int main() {
    int *arr = NULL;
    int size = 5;
    // Initial allocation using malloc
    arr = (int*)malloc(size * sizeof(int));
    if (arr == NULL) {
        perror("Initial allocation failed");
        return 1;
    }
    for (int i = 0; i < size; ++i) {
        arr[i] = i * 2;
    }
    // Resize the array
    int new_size = 10;
    int *new_arr = (int*)realloc(arr, new_size * sizeof(int));
    if (new_arr == NULL) {
        perror("Reallocation failed");
        free(arr); // Clean up original memory
        return 1;
    }
    arr = new_arr; // Update the pointer to the new memory block
    size = new_size;
    // Use the resized array
    for (int i = 0; i < new_size; ++i) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    free(arr); // Clean up memory
    return 0;
}

Use code with caution.

Comparison and best practices

Feature Manual Copy-and-Reallocate std::vector (C++) realloc() (C)
Language C and C++ C++ C and compatible C APIs
Ease of Use Difficult; requires manual memory management and error handling. Simple; automatic memory management and rich API. Moderately difficult; requires careful pointer handling and error checking.
Safety High risk of memory leaks and undefined behavior. Exception-safe and memory-safe. Requires careful error handling to avoid memory leaks.
Performance Can be inefficient if not optimized. Simple, single-element reallocations can be very costly. Optimizes reallocation internally (e.g., exponential growth). Potentially faster as it may not move the memory block if space allows.
Flexibility Provides full control over the allocation and copying process. High; offers various methods for size control and element manipulation. Resizes raw memory; limited to basic types in C++ due to lack of constructors.

In summary:

  • For C++, the best practice is to use std::vector. It provides a high-level, safe, and efficient way to manage dynamic arrays, preventing common memory management errors.
  • For C, realloc() is the standard and most direct method for resizing dynamically allocated memory. It is more efficient than a manual re-allocation loop when an in-place resize is possible.
  • The manual copy-and-reallocate method is an important educational exercise for understanding memory allocation but should be avoided in production code in favor of a tested library container.
Enjoyed this article? Share it with a friend.