×

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program is created to handle product lists for a company. As new products are added to the list, it expands; as products are subtracted, it contracts. As the amount of data grows, the memory makes room for the new data items. Programmers need to use dynamic memory management strategies in these situations. You will learn how to dynamically allocate memory within a C++ program in this article.

When we think of creation, we start from scratch. However, this is not what happens when a computer creates a variable. Instead, the computer simply assigns a memory cell from one of the many already-existing memory cells to the variable. It's like selecting a hotel room to stay from a large number of open or vacant previously occupied rooms.

Ways of Memory Allocation in C++

There are two ways to allocate memory for data storage. Which are:

Static Memory Allocation

Memory allocation is done statically or at compile time when the compiler sets aside space for named variables. At the time of compilation, the precise size and storage must be known; for array declaration, the size must be constant.

Dynamic memory allocation

Runtime allocation, also known as dynamic memory allocation, refers to the process of allocating memory while a program is running. The free store or a heap are two names for the memory section. In this scenario, the compiler does not need to know in advance the precise space or number of the item.

While the program is running, programmers can dynamically allocate storage space. However, programmers are unable to invent new variable names "on the fly," so dynamic allocation needs to meet the following two requirements:

  • There must be a dynamic space in the memory.
  • preserving the address needed to retrieve the variable from memory

We can use the unary operator "new" followed by the type to dynamically allot space.

Deleting the dynamic memory space

The pointer's address is being saved (so that space can be accessed)

This idea also includes memory de-allocation, which involves "cleaning up" space from variables or other data storage. The task of de-allocating dynamically created space falls to the programmer. We employ the delete operator to release dynamic memory.

The C++ program divides memory into two categories:

Stack: The memory of the stack is occupied by all variables declared inside of any function.

Heap: This is the program's unused memory, and it can be used to dynamically allocate memory at runtime. Heap Memory is allocated dynamically when it is dynamically accessed. In order to locate memory in heap section, we typically allocate arrays rather than just one character, integer, float, or other types of data.

Example for dynamic memory allocation :

Here is an example of using new code:

#include <iostream>
using namespace std;
int main()
{
 char* p  = NULL;       // Pointer initialized with NULL value
p = new char[40];     // Request memory for the variable
if(p==NULL)
cout<<" no memory is allocated";
else
cout<<"dynamic memory allocation done ";
    return 0;
}

Output :

dynamic memory allocation done

Explanation :

The term "new" denotes heap memory allocation and stack creation for arrays that are only declared. Any variables we declare inside the program or main function will receive memory inside the stack, regardless of where they are located. When we write something with new, the memory will be in a heap, so the address needs to be stored in an address variable. We can also write it like this because this is created in a heap. Another difference between heap and stack memory is that while heap memory does not automatically delete itself, the array is automatically created inside the stack and deleted once it exits the scope. Since it will remain there while your program is running, you should de-allocate it if you don't need it for the program or only need it temporarily. Heap memory must be de-allocated. This is crucial. When allocating resources, we write new. Later, if we no longer need them, we write delete []p. Since p is an array, it should use the subscript symbol [].


Related Topics

Floating Point Operations and Associativity in C, C++ and Java

In this tutorial, we are going to compare Floating-point operations and the concept of associativity. Before we apply the concept of associativity in the floating-point operations in all three programming...

3 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

Queue in C++

What is Queue? As the name suggests, the queue is the type of data structure that follows the FIFO (First In - First Out) mechanism. In simple words, it is...

4 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

Computing index using Pointers Returned by STL Functions in C++

In this tutorial we will learn how to compute index using pointers which returned by STL functions in C++. Many built-in C++ functions return pointers to memory places that provide...

2 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.