C++. Dynamic and static allocation of memory. Advantages and disadvantages. Allocating memory for single variables by the operators new and delete. Possible critical situations when allocating memory. Initialization when allocating memory




Dynamic and static allocation of memory. Advantages and disadvantages. Allocating memory for single variables by the operators new and delete. Possible critical situations when allocating memory. Initialization when allocating memory


Contents


Search other websites:

1. Dynamic and static (fixed) allocation of memory. The main differences

To work with arrays of information, programs must allocate memory for these arrays. To allocate memory for arrays of variables, the corresponding operators, functions, and so on are used. In the programming language of C++, the following methods of allocating memory are used:

1. Static (fixed) memory allocation. In this case, the memory is allocated only once at compile time. The size of the allocated memory is fixed and unchanged until the end of the program execution. An example of such a selection is the declaration of an array of 10 integers:

int M[10]; // The memory for the array is allocated once, the memory size is fixed

2. Dynamic memory allocation. In this case, a combination of the new and delete operators is used. The ‘new’ operator allocates memory for a variable (array) in a special memory area, called a “heap”. The ‘delete’ operator releases the allocated memory. Each ‘new’ operator must have its own delete statement.

2. Advantages and disadvantages of using dynamic and static methods of memory allocation

Dynamic allocation of memory in comparison with static allocation of memory gives following advantages:

  • memory is allocated as necessary;
  • no extra costs of unused memory. It allocates as much memory as needed and if necessary;
  • you can allocate memory for information arrays, the size of which is known to be unknown. Determining the size of the array is formed during the execution of the program;
  • it is convenient to reallocation the memory. Or in other words, it is convenient to allocate a new fragment for the same array, if you need to allocate additional memory or release unnecessary;
  • with the static way of allocating memory, it is difficult to reallocate the memory for the array variable, since it is already allocated fixedly. In the case of a dynamic allocation way, this is done simply and conveniently.

Advantages of static memory allocation:

  • static (fixed) allocation of memory is better to use when the size of an array of information is known and is unchanged throughout the execution of the entire program;
  • static memory allocation does not require additional release operations with the delete operator. This implies a reduction of programming errors. Each new operator must have its own delete statement;
  • the naturalness of the representation of program code, which operates with static arrays.

Depending on the task, the programmer should be able to correctly determine which method of allocating memory is suitable for a particular variable (array).

3. How to allocate memory by the new operator for a single variable? General form

The general form of memory allocation for a single variable by the new operator is as follows:

ptrName = new type;

where

  • ptrName – the name of the variable (pointer) that will point to the allocated memory;
  • type – the type of variable. The size of the memory is allocated enough to place the value of a variable of this type type in it.

4. How to free memory allocated for a single variable using the ‘delete’ operator? General form

If the memory for the variable is allocated using the ‘new’ operator, then after the use of the variable is completed, this memory must be freed by the ‘delete’ operator. In C++, this is a prerequisite. If memory is not freed, the memory will remain allocated (busy), but no program can use it. In this case, there will be a “memory leak“.

In Java, C#, you do not need to release memory after selection. This is done by the “garbage collector“.

The general form of the delete operator for a single variable is:

delete ptrName;

where ptrName is the name of the pointer for which the memory was previously allocated using the ‘new’ operator.

After the ‘delete’ operator is executed, the ptrName points to an arbitrary memory location that is not reserved (allocated).

5. Examples of allocation (new) and deletion (delete) of memory for pointers of base types

The examples demonstrate the use of the new and delete operators. The examples are simplified.

Example 1. A pointer to int. The simplest example

// memory allocation by operator new
int * p; // pointer to int int

p = new int; // allocate memory for the pointer
*p = 25; // save the values into memory

// use of memory allocated for the pointer
int d;
d = *p; // d = 25

// release the memory allocated for the index - mandatory
delete p;

Example 2. Pointer to double type

// allocating memory for a pointer to 'double'
double * pd = nullptr;

pd = new double; // allocate memory
*pd = 10.89; // save values

double d = *pd; // d = 10.89 - using in program
if (pd != nullptr) // free the memory
    delete pd;

6. What is a “memory leak”?

A “memory leak” is when the memory for a variable is allocated by the ‘new’ operator, and when the program finishes, it is not released by the ‘delete’ operator. In this case, the memory in the system remains busy, although there is no need to use it, since the program that used it has already completed its work for a long time.

Memory leak” is a typical programmer error. If the “memory leak” is repeated many times, then a possible situation when all available memory in the computer will be “occupied”. This will lead to unpredictable consequences of the operating system.






7. How to allocate memory by the operator ‘new’ with interception of a critical situation at which memory can not be allocated? Exception bad_alloc. Example

When using the ‘new’ operator, a situation may occur when memory is not allocated. Memory may not be distinguished in the following situations:

  • if there is no free memory;
  • the amount of free memory is less than the one specified in the ‘new’ operator.

In this case, the exception bad_alloc occurs. The program can intercept this situation and process it accordingly.

Example. The example takes into account the situation when the memory can not be allocated by the operator ‘new’. If the attempt is successful, then the program continues. If the attempt fails, it exits from the function with return code -1.

int main()
{
    // declare an array of pointers to a float
    float * ptrArray;

    try
    {
        // try to allocate memory for 10 items of 'float' type
        ptrArray = new float[10];
    }
    catch (bad_alloc ba)
    {
        cout << "Exception. Memory is not allocated" << endl;
        cout << ba.what() << endl;
        return -1; // exit
    }

    // if everything is in order, then use an array
    for (int i = 0; i < 10; i++)
        ptrArray[i] = i * i + 3;

    int d = ptrArray[5];
    cout << d << endl;

    delete[] ptrArray; // release the memory allocated for the array

    return 0;
}

8. Allocating memory for a variable with simultaneous initialization. General form. Example

The memory allocation operator for a single variable allows for simultaneous initialization of this variable.

In general, allocating memory for a variable with simultaneous initialization has the form

ptrName = new type(value)

where

  • ptrName – the name of the pointer variable for which memory is allocated;
  • type – type pointed to by ptrName;
  • value – the value that is set for the selected area of memory (value by pointer).

Example. Memory allocation for variables with simultaneous initialization. Below is the main() function for the console application. The allocation of memory with simultaneous initialization is demonstrated. It also takes into account the situation when an attempt to allocate memory fails (exception bad_alloc).

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
    // memory allocation with simultaneous initialization
    float * pF;
    int * pI;
    char * pC;

    try
    {
        // Trying to allocate memory for variables with simultaneous initialization
        pF = new float(3.88); // *pF = 3.88
        pI = new int(250); // *pI = 250
        pC = new char('M'); // *pC = 'M'
    }
    catch (bad_alloc ba)
    {
        cout << "Exception. Memory is not allocated" << endl;
        cout << ba.what() << endl;
        return -1; // exit
    }

    // if memory is allocated, then the use of pointers pF, pI, pC
    float f = *pF; // f = 3.88
    int i = *pI; // i = 250;
    char c;

    c = *pC; // c = 'M'

    // output the initialized values
    cout << "*pF = " << f<< endl;
    cout << "*pI = " << i << endl;
    cout << "*pC = " << c << endl;

    // release the memory, earlier allocated for pointers
    delete pF;
    delete pI;
    delete pC;

    return 0;
}


Related topics