Lesson 03: Dynamic Memory

Dynamic memory allocation, or heap memory allocation, allocates memory during program execution. In contrast to static memory allocation, which assigns memory at compile time, dynamic memory allocation allows programmers to allocate and deallocate memory as needed during the program's runtime.

Significance of Dynamic Memory Allocation:

Dynamic memory allocation provides several advantages, including:

  • Flexibility: It enables programmers to allocate memory for data structures of varying sizes that are not known beforehand.
  • Efficiency: It allows for efficient memory utilization by allocating memory only when needed and deallocating it when no longer needed.
  • Adaptability: It supports dynamic data structures, such as linked lists and trees, that can grow or shrink as the program runs.

Mechanisms for Dynamic Memory Allocation

C++ provides two primary tools for dynamic memory allocation:

  • new operator: The new operator allocates memory from the heap and returns a pointer to the allocated block.
    int *ptr = new int; // Allocates memory for an integer and returns a pointer to it
  • delete operator: The delete operator deallocates memory previously allocated by the new operator.
    delete ptr; // Deallocates the memory pointed to by ptr

Example of Dynamic Memory Allocation:

Consider a program that needs to store an unknown number of integers. The program can allocate memory for an array of integers as needed using dynamic memory allocation.

int n;                  // Number of integers to store
cin >> n;               // Read the number of integers
int *arr = new int[n];  // Allocate memory for an array of n integers

for (int i = 0; i < n; ++i) {
    cin >> arr[i];      // Read and store each integer
}
// Use the array of integers
for (int i = 0; i < n; ++i) {
    cout << arr[i] << " ";
}
delete[] arr;           // Deallocate the memory for the array

In this example, the program allocates memory for an array of integers using the new operator, uses the array to store and access the integers, and then deallocates the memory using the delete operator.

Dynamic memory allocation is a powerful tool in C++ programming, enabling programmers to create flexible and efficient applications that handle data of varying sizes and requirements. However, it is crucial to properly manage dynamically allocated memory to avoid memory leaks, which occur when memory is allocated but never deallocated, leading to inefficient memory usage and potential program crashes.