Tutorial Study Image

Dynamic memory in C++


June 12, 2023, Learn eTutorial
244

Programming situations frequently involve dynamic data or input, where the number of data items changes as the program is running. An actual instance where the application is created to process employee listings for a company As names are added to the list, it expands; as names are removed, it contracts. The memory allocates space to the list to accommodate extra data items as the name lengthens. Programmers need to use dynamic memory management strategies in these instances.

Before program execution, all memory requirements were determined by declaring the variables required. The memory requirements of a program might, however, only be known at runtime in some circumstances. For example, when the amount of memory required is determined by user input. In these situations, programs must dynamically allocate memory, which is why the C++ language has built-in support for the operator’s new and delete. The topic of dynamic memory allocation in C++ is covered in this article.

C++ Memory Allocation

The process of designating memory space in a program for variables, instances of structures, and classes is known as memory allocation. When a program is executing, memory is allocated. The new operator is used to allocate memory, whereas the delete operator is used to deallocate memory.

For a C++ program, the memory architecture consists of :

  • Code Segment: This is where the compiled program and executive instructions are kept. You can only read it. Code segments are stored underneath the stack and the heap to prevent overwriting of those two structures.
  • Data Segment: This is where global variables as well as static variables are maintained. It is not intended to be read-only.
  • Stack: A stack is often pre-allocated memory. The stack is a last-in, first-out data structure. Every new variable is added to the stack. When a variable exits its scope, memory is released. The memory space occupied by a stack variable can then be used by other variables once it has been released. Functions push as well as pop local variables, which causes the stack to expand and contract. It saves local information, return addresses, function-passed arguments, and the memory's current condition.

Static Memory Allocation in C++

Memory is allocated and deallocated by the compiler independently in static memory allocation. At the time of compilation, we must specify the amount of memory that is necessary. The compiler determines how much memory these variables will require during static memory allocation and fixes a place for their storage. The locations of the variables that will be stored are saved using a table. However, the variable is not given any physical memory at compile time.

Dynamic Memory Allocation in C++

Memory is allocated dynamically while a program is running. However, in this instance, it is the programmer's duty to deallocate the dynamically allocated memory when it is no longer required. Otherwise, memory leaks occur. While a program is running, programmers can allocate storage space dynamically, but they cannot invent new variable names "on the fly," hence dynamic allocation needs to meet two requirements:

  • constructing a dynamic memory space
  • preserving its address within a pointer (so that the space can be easily accessed)

Memory de-allocation is another aspect of this idea, where space is "cleaned up" for variables or other data storage. It is the programmer's responsibility to de-allocate dynamically produced space. We employ the delete operator to release dynamic memory. Alternatively, the term "dynamic memory allocation" refers to manually managing memory for dynamic memory allocation.

Understanding C++ Memory Leaks

Memory leaks are caused by improper memory allocation and deallocation practices. Most frequently, it occurs when allocating dynamic memory. The programmer is in charge of allocating the memory needed by pointers because C++ does not have automatic garbage collection as Java does.

A real-world illustration of a memory leak is the misuse of an elevator in a hotel. Let's say you rent an apartment in a 19-story building. You hit the button to summon the elevator because you wanted to go to the 10th floor. For 20 minutes, the elevator's status has been showing as the basement. When you investigate, you discover that children were playing in the basement and had blocked the elevator entrance. Then you understand that something is wrong.

Similarly to this, a pointer should release the memory it used once it has finished its actions. so that memory can be appropriately managed and used by other variables.

The memory that has been allocated can be deleted by using the delete keyword.

Dynamic memory allocation for Arrays

If you, a programmer, want to allot memory for a string of 40 characters, that is an array of characters. The next example shows how programmers can allocate memory dynamically using the same technique.


char* val  = NULL;       // Pointer initialized with NULL value
val = new char[40];     // Request memory for the variable
 

Dynamic allocation program using constructor


#include <iostream>
using namespace std; 

class stud {
public:
    stud()
    {
        cout << "Constructor Used" << endl;
    }
    ~stud()
    {
        cout << "Destructor Used" << endl;
    }
};

int main()
{
    stud* S = new stud[6];
    delete[] S;
}

 

Output:


Constructor Used
Constructor Used
Constructor Used
Destructor Used
Destructor Used
Destructor Used

Uses of Dynamic Memory Allocation

  • Sometimes the amount of memory needed to store some data is not known in advance. We can allocate memory with variable size at runtime by using dynamic memory allocation.
  • It gives the programmer flexibility. Memory can be allocated and released as needed by programmers.

For dynamic memory allocation in C, we use the calloc() , malloc() methods. Using free(), we can deallocate that memory. C++ also provides support for these functions. However, utilizing these functions in C++ is discouraged.

The two unary operators new and delete in C++ enable effective dynamic memory allocation and deallocation.

Arrays' Dynamic Memory Allocation in C++

The size of an array is frequently unknown until runtime. In these cases, dynamic memory allocation is useful. It improves memory management effectiveness.

The syntax for allocating a memory block for an array:


pointer_variable = new data_type[size];
 

syntax If the multidimensional array is m x n in size:


pointer_variable = new data_type[m][n];
 

The following syntax will deallocate any array's memory space:


delete [ ] pointer_variable;
 

A very simple example of the dynamic memory allocation mainly for arrays


#include <iostream>
using namespace std;

int main() {
  int *ptr = new(nothrow) int[20];
  
  if(!ptr){
      cout<<"Sorry Failed! Memory not available."<<endl;
      exit(1);
  }
  
  for(int i=0; i<20; i++){
      ptr[i]=i+1;
  }
  
  for(int i=0; i<20; i++){
      cout<<ptr[i]<<" ";
  }
  
  delete [] ptr;
  return 0;
}

 

Output:


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20