blog icon indicating copy to clipboard operation
blog copied to clipboard

C++ Dynamic Memory Allocation

Open qingquan-li opened this issue 2 years ago • 0 comments

Concept: Variable may be created and destroyed while a program is running.

To dynamically allocate memory means that a program, while running, asks the computer to set aside a chunk of unused memory large enough to hold a variable of a specific data type.

Dynamic Memory Allocation

new operator:

The way a C++ program requests dynamically allocated memory is through the new operator.

Assume a program has a pointer to an int defined as:

int* iptr = nullptr;

Here is an example of how this pointer may be used with the new operator:

iptr = new int;

Once the statement executes, iptr will contain the address of the newly allocated memory.

A value may be stored in this new variable by dereferencing the pointer:

// assign 25 to the dereferenced pointer: *iptr
*iptr = 25;

new an array:

A more practical use of the new operator is to dynamically create an array. Here is an example of how a 10-element array of integers may be allocated:

iptr = new int[10];

Once the array is created, the pointer may be used with subscript notation to access it. For instance, the following loop could be used to store the value 1 in each element:

for (int count = 0; count < 10; count++)
    iptr[count] = 1;

delete operator:

When a program is finished using a dynamically allocated chunk of memory, it should release it for future use. The delete operator is used to free memory that was allocated with new.

Here is an example of how delete is used to free a single variable, pointed to by iptr:

delete iptr;

If iptr points to a dynamically allocated array, the [] symbol must be placed between delete and iptr :

delete [] iptr;

Memory Leaks and Dangling Pointers

  • A memory leak occurs if no-longer-needed dynamic memory is not freed. The memory is unavailable for reuse within the program.

    • Solution: free up dynamic memory after use
  • A pointer is dangling if it contains the address of memory that has been freed by a call to delete.

    • Solution: set such pointers to nullptr as soon as the memory is freed.

Example01:

#include <iostream>
using namespace std;

int main() {
    // int* iptr = new int;   // create an integer object (a space) in memory
    // *iptr = 25;
    // cout << *iptr << endl; // 25

    int num_values;
    int* iptr = nullptr;

    cout<< "How many values do you want to store? ";
    cin >> num_values;
    // Dynamically allocate an array to hold the values.
    iptr = new int[num_values];

    // Store the value 1 in each element.
    for (int count = 0; count < num_values; count++)
        iptr[count] = 1;

    for (int count = 0; count < num_values; count++) {
        cout << iptr[count] << " ";
    }

    // Free dynamically allocated memory.
    // Avoid memory leaks (the value of the original memory space is accessed by other objects).
    delete [] iptr;
    // Make iptr a null pointer.
    // Avoid dangling pointer (the pointer pointing to an empty memory space).
    iptr = nullptr;

    return 0;
}

Output:

How many values do you want to store? 10
1 1 1 1 1 1 1 1 1 1 

Example02:

// This program totals the sales amounts for any number of days.
// The amounts are stored in a dynamically allocated array.

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double* sales = nullptr; // To dynamically allocate an array
    double total = 0.0;      // Accumulator
    int num_days;

    cout << "How many days of sales amounts do you wish to process? ";
    cin >> num_days;

    // Dynamically allocate an array large enough to hold
    // that many days of sales amounts.
    sales = new double[num_days];

    // Get the sales amounts for each day.
    cout << "Enter the sales amounts below.\n";
    for (int i = 0; i < num_days; i++) {
        cout << "Day " << (i + 1) << ": ";
        cin >> sales[i];
    }

    // Calculate the total sales
    for (int i = 0; i < num_days; i++)
        total += sales[i];

    cout << fixed << showpoint << setprecision(2);
    cout << "Total Sales: $" << total;

    // Free dynamically allocated memory
    delete [] sales;
    sales = nullptr; // Make sales a null pointer.

    return 0;
}

Output:

How many days of sales amounts do you wish to process? 3
Enter the sales amounts below.
Day 1: 100
Day 2: 100.5
Day 3: 108
Total Sales: $308.50

qingquan-li avatar Jul 06 '22 19:07 qingquan-li