×

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

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

Inheritance in C++ vs Java

Just like we inherit traits from our parents, object-oriented programming has a concept called inheritance. In terms of object-oriented programming, a class's traits and behaviours, or its data and methods,...

4 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

4 Pillars of OOPs

OOPs OOPS means Object Oriented Programming System Structure. Object oriented Programming is defined as an approach that provides a way of modularizing programs by creating partitioned memory area for both data...

11 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 minutes read.