Dynamic Memory Allocation Using Pointers

Dynamic memory allocation in C++ provides a way to allocate memory during runtime, enabling the creation of data structures whose size is not known at compile time. This is achieved using pointers and functions like new and delete. Dynamic memory allocation is crucial for building flexible and scalable applications where memory requirements may vary dynamically.

Introduction to Dynamic Memory Allocation in C++:

In C++, dynamic memory allocation is managed through pointers. Unlike static memory allocation, where memory is allocated at compile time, dynamic memory allocation occurs during program execution. This allows for the creation of data structures whose size can vary based on user input or runtime conditions.

Dynamic Memory Management Functions:

  • new Operator
  • The new operator is used to dynamically allocate memory for a single variable or an array.
  • Syntax: pointer_variable = new data_type; or pointer_variable = new data_type[size];
  • Example: int *ptr = new int; or int *arr = new int[5];
  • delete Operator:
  • The delete operator is used to release dynamically allocated memory.
  • Syntax: delete pointer_variable; or delete[] pointer_variable;
  • Example: delete ptr; or delete[] arr;

Benefits of Dynamic Memory Allocation:

  1. Flexibility: Dynamic memory allocation allows for the creation of data structures whose size can be determined during runtime, offering flexibility in handling varying memory requirements.
  2. Resource Optimization: Memory is allocated only when needed, optimizing resource usage and avoiding wastage of memory.
  3. Dynamic Data Structures: Dynamic memory allocation facilitates the creation of dynamic data structures like linked lists, trees, and dynamic arrays, enabling efficient data management.
  4. Memory Reuse: Dynamically allocated memory can be reused for different purposes during program execution, enhancing memory utilization.

C++ Program Demonstrating Dynamic Memory Allocation:

#include <iostream>
using namespace std;

int main() {
    int *ptr; // Declare a pointer to int
    
    ptr = new int; // Dynamically allocate memory for a single integer
    
    if (ptr == nullptr) {
        cout << "Memory allocation failed." << endl;
        return 1;
    }
    
    *ptr = 10; // Assign a value to the dynamically allocated memory
    
    cout << "Value at dynamically allocated memory: " << *ptr << endl;
    
    delete ptr; // Deallocate the dynamically allocated memory
    
    return 0;
}

Explanation of the Program:

  1. Declaration of Pointer: int *ptr;
    • Declare a pointer ptr to an integer. This pointer will be used to store the address of dynamically allocated memory.
  2. Dynamic Memory Allocation: ptr = new int;
    • Dynamically allocate memory for a single integer using the new operator.
    • The new int expression returns the address of the allocated memory, which is assigned to the pointer ptr.
  3. Memory Allocation Check:
    • Check if memory allocation was successful using if (ptr == nullptr).
    • If memory allocation fails, output an error message and exit the program.
  4. Assignment of Value: *ptr = 10;
    • Assign a value of 10 to the memory location pointed to by ptr.
  5. Output Value: cout << "Value at dynamically allocated memory: " << *ptr << endl;
    • Output the value stored at the dynamically allocated memory location pointed to by ptr.
  6. Deallocation of Memory: delete ptr;
    • Deallocate the dynamically allocated memory using the delete operator to avoid memory leaks.

This program demonstrates the basic process of dynamic memory allocation in C++, including memory allocation, assignment of values, outputting the value, and deallocation of memory to prevent memory leaks.

Given below are few more examples to demonstrate dynamic memory allocation in C++

Dynamic Memory Allocation for Array of Integers

Introduction: This program demonstrates dynamic memory allocation for an array of integers using pointers. It dynamically allocates memory for an array of integers, initializes the array with values, and then deallocates the memory.

#include <iostream>

int main() {
    const int size = 5;
    
    // Dynamic memory allocation for an array of integers
    int *ptr = new int[size]; // Allocate memory for an array of integers

    // Initialize the array with values
    for (int i = 0; i < size; ++i) {
        ptr[i] = i + 1;
    }

    // Print the values of the array
    std::cout << "Array values: ";
    for (int i = 0; i < size; ++i) {
        std::cout << ptr[i] << " ";
    }
    std::cout << std::endl;

    delete[] ptr; // Deallocate memory

    return 0;
}

Explanation:

  • const int size = 5;: Specifies the size of the array of integers.
  • int *ptr = new int[size];: Dynamically allocates memory for an array of integers of size size and assigns the address of the allocated memory to the pointer ptr.
  • Initialization of the array:
    • for (int i = 0; i < size; ++i) { ptr[i] = i + 1; }: Initializes each element of the array with values from 1 to size.
  • Printing the values of the array:
    • std::cout << "Array values: ";: Prints the label for the array values.
    • for (int i = 0; i < size; ++i) { std::cout << ptr[i] << " "; }: Prints each element of the array using the pointer ptr.
  • delete[] ptr;: Deallocates the dynamically allocated memory for the array.

The program above demonstrates dynamic memory allocation for an array of integers using pointers.

Dynamic Memory Allocation for 2D Array

Introduction: This program demonstrates dynamic memory allocation for a 2D array using pointers. It dynamically allocates memory for a 2D array, initializes the array with values, and then deallocates the memory.

#include <iostream>

int main() {
    const int rows = 3;
    const int cols = 4;
    
    // Dynamic memory allocation for a 2D array
    int **ptr = new int*[rows]; // Allocate memory for array of row pointers
    
    // Allocate memory for each row
    for (int i = 0; i < rows; ++i) {
        ptr[i] = new int[cols];
    }

    // Initialize the 2D array with values
    int value = 1;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            ptr[i][j] = value++;
        }
    }

    // Print the values of the 2D array
    std::cout << "2D Array values:" << std::endl;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            std::cout << ptr[i][j] << " ";
        }
        std::cout << std::endl;
    }

    // Deallocate memory for each row
    for (int i = 0; i < rows; ++i) {
        delete[] ptr[i];
    }
    
    delete[] ptr; // Deallocate memory for array of row pointers

    return 0;
}

Explanation:

  • const int rows = 3; and const int cols = 4;: Specifies the number of rows and columns in the 2D array.
  • int **ptr = new int*[rows];: Dynamically allocates memory for an array of row pointers of size rows and assigns the address of the allocated memory to the pointer ptr.
  • Allocation of memory for each row:
    • for (int i = 0; i < rows; ++i) { ptr[i] = new int[cols]; }: Dynamically allocates memory for each row of the 2D array of size cols.
  • Initialization of the 2D array:
    • Nested loop: for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { ... } }: Initializes each element of the 2D array with sequential values.
  • Printing the values of the 2D array:
    • Nested loop: for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { ... } }: Prints each element of the 2D array.
  • Deallocating memory:
    • for (int i = 0; i < rows; ++i) { delete[] ptr[i]; }: Deallocates memory for each row of the 2D array.
    • delete[] ptr;: Deallocates memory for the array of row pointers.

The above program demonstrates dynamic memory allocation for a 2D array using pointers.

Dynamic Memory Allocation for Array of Strings

Introduction: This program demonstrates dynamic memory allocation for an array of strings using pointers. It dynamically allocates memory for an array of strings, initializes the strings, and then deallocates the memory.

#include <iostream>
#include <cstring>

int main() {
    const int size = 3;
    const int maxStringLength = 20;
    
    // Dynamic memory allocation for an array of strings
    char **ptr = new char*[size]; // Allocate memory for array of string pointers
    
    // Allocate memory for each string
    for (int i = 0; i < size; ++i) {
        ptr[i] = new char[maxStringLength];
    }

    // Initialize the array of strings
    strcpy(ptr[0], "Hello");
    strcpy(ptr[1], "Dynamic");
    strcpy(ptr[2], "Memory");

    // Print the strings
    std::cout << "Strings:" << std::endl;
    for (int i = 0; i < size; ++i) {
        std::cout << ptr[i] << std::endl;
    }

    // Deallocate memory for each string
    for (int i = 0; i < size; ++i) {
        delete[] ptr[i];
    }
    
    delete[] ptr; // Deallocate memory for array of string pointers

    return 0;
}

Explanation:

  • const int size = 3; and const int maxStringLength = 20;: Specifies the number of strings in the array and the maximum length of each string.
  • char **ptr = new char*[size];: Dynamically allocates memory for an array of string pointers of size size and assigns the address of the allocated memory to the pointer ptr.
  • Allocation of memory for each string:
    • for (int i = 0; i < size; ++i) { ptr[i] = new char[maxStringLength]; }: Dynamically allocates memory for each string of maximum length maxStringLength.
  • Initialization of the array of strings:
    • strcpy(ptr[0], "Hello");, strcpy(ptr[1], "Dynamic");, strcpy(ptr[2], "Memory");: Initializes each string with specific values using the strcpy function.
  • Printing the strings:
    • for (int i = 0; i < size; ++i) { std::cout << ptr[i] << std::endl; }: Prints each string.
  • Deallocating memory:
    • for (int i = 0; i < size; ++i) { delete[] ptr[i]; }: Deallocates memory for each string.
    • delete[] ptr;: Deallocates memory for the array of string pointers.

The program above demonstrates dynamic memory allocation for an array of strings using pointers.

Dynamic memory allocation is a powerful feature of C++ that allows for efficient memory management and the creation of dynamic data structures.