Metadata

  • 📅 Date :: 12-06-2025
  • 🏷️ Tags :: cpp

Notes

Detailed Notes on Dynamic Memory in C++

What is Dynamic Memory?

Dynamic memory refers to memory that is allocated during program execution, rather than at compile time. It is allocated in the heap, a region of memory used for variables whose size is not known at compile time or may change during execution. This is particularly useful when you don’t know in advance how much memory you will need, such as when accepting user input, working with large data sets, or dealing with variables whose sizes can vary during runtime.

In C++, dynamic memory allocation is done using the new operator, and when you no longer need that memory, you use the delete operator to deallocate it.

Why Use Dynamic Memory?

  • Flexibility: Dynamic memory allows the program to request memory as needed, making it more flexible than statically allocated memory, where the size must be known at compile time.
  • Efficient Memory Usage: By allocating memory only when required, programs can optimize memory usage, especially when the amount of data varies during execution.

How to Allocate Dynamic Memory in C++

1. Allocating a Single Variable

To allocate memory for a single variable in dynamic memory, use the new operator. Here’s an example with an integer:

#include <iostream>
 
int main() {
    int* pnum = nullptr;  // Declare a pointer and initialize it to nullptr for safety.
 
    // Dynamically allocate memory for one integer in the heap.
    pnum = new int;
 
    // Assign a value to the allocated memory
    *pnum = 21;
 
    // Display the address stored in the pointer and the value at that address
    std::cout << "Address: " << pnum << "\n";
    std::cout << "Value: " << *pnum << "\n";
 
    // Deallocate the memory
    delete pnum;  // Freeing up the memory when no longer needed.
 
    return 0;
}
 

In this example:

  • The new int operator allocates memory for one integer in the heap.
  • The pointer pnum stores the memory address returned by new.
  • The value 21 is assigned to the dynamically allocated memory.
  • delete is used to release the memory after use to prevent memory leaks.

2. Allocating Memory for Arrays Dynamically

When the size of an array is unknown at compile time (like when accepting user input), dynamic memory allocation becomes useful. Here’s how you can dynamically allocate memory for an array:

#include <iostream>
 
int main() {
    int size;
 
    // Ask user for how many grades to enter
    std::cout << "How many grades to enter: ";
    std::cin >> size;
 
    // Dynamically allocate an array for 'size' number of grades
    char* pgrades = new char[size];
 
    // Collect grades from the user
    for (int i = 0; i < size; ++i) {
        std::cout << "Enter grade " << (i + 1) << ": ";
        std::cin >> pgrades[i];
    }
 
    // Display the grades entered by the user
    std::cout << "The grades entered are: ";
    for (int i = 0; i < size; ++i) {
        std::cout << pgrades[i] << " ";
    }
 
    // Free the dynamically allocated array
    delete[] pgrades;  // Use delete[] for arrays
 
    return 0;
}
 

Explanation:

  • new char[size] allocates memory in the heap for an array of char with the size specified by the user.
  • A loop collects the grades from the user.
  • The grades are displayed, and once they are no longer needed, delete[] pgrades is used to deallocate the memory, preventing a memory leak.

Why is new and delete Important?

  • new: Allocates memory on the heap. It can allocate a single variable (new int) or an array (new int[5]).
  • delete: Frees up memory allocated with new. If you allocate memory dynamically with new, failing to deallocate it with delete will result in a memory leak—unused memory that the program cannot access or reuse, eventually causing the program to consume more memory than it needs.

For arrays, always use delete[] instead of delete to ensure proper memory deallocation.


Key Concepts & Best Practices

1. Null Initialization for Pointers

When you declare a pointer, it’s a good practice to initialize it to nullptr to prevent accessing uninitialized memory. If you don’t assign a pointer to a specific address immediately, setting it to nullptr ensures that any accidental dereferencing will not lead to undefined behavior.

int* pnum = nullptr;  // Safe initialization of a pointer
 

2. Memory Leaks

Memory leaks occur when dynamically allocated memory is not deallocated. This leads to the exhaustion of memory resources, causing slowdowns or crashes in programs. To avoid memory leaks:

  • Always free dynamically allocated memory using delete (for single variables) or delete[] (for arrays) when it is no longer needed.

3. Dynamic Memory Allocation Should Be Used Wisely

Dynamic memory is especially useful when the required memory size is not known at compile time. However, excessive dynamic memory allocation or improper management can complicate your code and make it harder to debug. Therefore, use it only when necessary.

4. Using Dynamic Memory with Arrays

When using dynamic memory for arrays, remember:

  • Arrays allocated with new[] should be freed using delete[] (note the square brackets).
  • Always check if the allocation is successful before accessing the allocated memory. If memory allocation fails, new will throw a std::bad_alloc exception (if exceptions are enabled).

Example: Flexible Program with User Input

Consider the following example where we dynamically allocate memory for an array based on user input:

#include <iostream>
 
int main() {
    int size;
 
    // Ask user for how many grades to enter
    std::cout << "How many grades to enter: ";
    std::cin >> size;
 
    // Dynamically allocate memory for grades
    char* pgrades = new char[size];
 
    // Input grades
    for (int i = 0; i < size; ++i) {
        std::cout << "Enter grade " << (i + 1) << ": ";
        std::cin >> pgrades[i];
    }
 
    // Output grades
    std::cout << "The grades are: ";
    for (int i = 0; i < size; ++i) {
        std::cout << pgrades[i] << " ";
    }
 
    // Clean up dynamically allocated memory
    delete[] pgrades;
 
    return 0;
}
 

In this example:

  • The user is asked to input how many grades they want to enter.
  • The program dynamically allocates memory based on the user’s input.
  • Once the grades are input, the program displays them.
  • Afterward, it deallocates the memory using delete[] to avoid memory leaks.

Conclusion

Dynamic memory in C++ provides flexibility and efficiency by allocating memory at runtime. Using new and delete correctly allows you to manage memory effectively, especially in programs with variable data sizes or uncertain memory needs. Always ensure to deallocate memory when you’re done using it to avoid memory leaks.


References