realloc() function in C++

In this guide, you will learn what is realloc() function is in C++ programming and how to use it with an example.

1. realloc() Function Overview

The realloc() function in C++ is used to resize the memory block that was previously allocated with a call to malloc() or calloc(). It can increase or decrease the size of the allocated block. If necessary, realloc() may move the memory block to a new location, and in such cases, it returns the new address. It's included in the C standard library <cstdlib> in C++.

Signature:

void* realloc(void* ptr, size_t size);

Parameters:

- ptr: A pointer to the memory block previously allocated with malloc() or calloc(). If ptr is NULL, the realloc() function behaves like malloc().

- size: The new size for the memory block in bytes.

2. Source Code Example

#include <iostream>
#include <cstdlib>

int main() {
    int* arr;
    int n = 5; // Initial number of integers

    // Dynamically allocate memory for 5 integers using malloc
    arr = (int*) malloc(n * sizeof(int));

    for(int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }

    // Resize the allocated memory to hold 10 integers
    int new_size = 10;
    arr = (int*) realloc(arr, new_size * sizeof(int));

    // Initialize the newly allocated space
    for(int i = n; i < new_size; i++) {
        arr[i] = i + 1;
    }

    // Print the resized array
    for(int i = 0; i < new_size; i++) {
        std::cout << arr[i] << " ";
    }

    // Free the allocated memory
    free(arr);

    return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10

3. Explanation

1. We start by dynamically allocating memory for an array of 5 integers using malloc().

2. We then assign values to this initial memory.

3. We use realloc() to resize the allocated memory to hold 10 integers.

4. The additional memory is then initialized.

5. We print the contents of the resized array.

6. After utilizing the dynamically allocated memory, we release it using the free() function.


Comments