Skip to main content

C++ Dynamic Memory Allocation

C++ Advanced


C++ Dynamic Memory Allocation

Often some situation arises in programming where data or input is dynamic in nature, i.e. the number of data item keeps changing during program execution. A live scenario where program is developed to process lists of employees of an organization. The list grows as the names are added and shrinks as the names get deleted. With the increase in name the memory allocate space to the list to accommodate additional data items. Such situations in programming require dynamic memory management techniques.

In this chapter you will learn about how to dynamically allocate memory within a C++ program.

What is memory Allocation?

There are two ways via which memories can be allocated for storing data. The two ways are:
  1. Compile time allocation or static allocation of memory: where the memory for named variables is allocated by the compiler. Exact size and storage must be known at compile time and for array declaration the size has to be constant.
  2. Run time allocation or dynamic allocation of memory: where the memory is allocated at run time and the allocation of memory space is done dynamically within the program run and the memory segment is known as heap or the free store. In this case the exact space or number of item does not have to be known by the compiler in advance. Pointers play a major role in this case.

What is Dynamic memory allocation?

Programmers can dynamically allocate storage space while the program is running, but programmers cannot create new variable names “on the fly”, and for this reason dynamic allocation requires two criteria:
  • Creating the dynamic space in memory
  • Storing its address in a pointer (so that the space can be accessed)
Memory de-allocation is also a part of this concept where the “clean-up” of space is done for variables or other data storage. It is the job of the programmer to de-allocate dynamically created space. For de-allocating dynamic memory, we use the delete operator. In other words, dynamic memory Allocation refers to performing memory management for dynamic memory allocation manually.
Memory in your C++ program is divided into two parts:
  • stack: All variables declared inside any function takes up memory from the stack.
  • heap: It is unused memory of the program and can be used to dynamically allocate the memory at run time.

Allocating space with new

To allocate space dynamically, use the unary operator new, followed by the type being allocated.
Here is a code snippet showing the use of new:
new int; //dynamically allocates an integer type
new double; // dynamically allocates an double type
new int[60];
The above declared statements are not so useful as the allocated space has no names. But the lines written below are useful:
int * p; // declares a pointer p
p
= new int;  // dynamically allocate an int for loading the address in p
double * d;  // declares a pointer d
d
= new double;  // dynamically allocate a double and loading the address in p
The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. malloc() allocates requested size of bytes and returns a pointer to first byte of allocated space. The main benefit of new over malloc() is that new doesn’t just allocate memory, it constructs objects which is a prime concept of C++. When programmers think that the dynamically allocated variable is not required any more, they can use the delete operator to free up memory space. The syntax of using this is:
delete var_name;
Here is a simple program showing the concept of dynamic memory allocation:
Example:
#include <iostream>
using namespace std;

int main()
{
double* val = NULL;
val
= new double;
*val = 38184.26;
cout
<< "Value is : " << *val << endl;
delete val;
}

Dynamic Memory Allocation for Arrays

If you as a programmer; wants to allocate memory for an array of characters, i.e., string of 40 characters. Using that same syntax, programmers can allocate memory dynamically as shown below.
char* val  = NULL;       // Pointer initialized with NULL value
val
= new char[40];     // Request memory for the variable

Another Dynamic Allocation Program Using Constructor

Example:
#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;
}

Comments

For Programs Click Here

Popular posts from this blog

Python Lists

Python Lists Dealing with data in a structured format is quiet generous, and this is possible if those data are set accordingly in a specific manner. So, Python provides these data structures named ‘lists’ and ‘tuples’ that are used to organize data in  single set. Python has 6 built-in sequences and among them the most famous are “lists and tuples”. The lists are containers that hold a number of other objects in a given order. It usually puts into practice the sequence protocol and allows programmers to add or remove objects from that sequence. Each element of the sequence is assigned a number i.e. he index and the first index is 0 (zero). This versatile data-type of Python is written in a sequence of list separated by commas between expressions. Creating Lists To build a list, just put a number of expressions in square brackets. The syntax is: Syntax: lst1 = [ ] # lst1 is the name of the list lst2 = [ expression1 , …. , expression_N ] Example: #!/usr/bin/python ls...

C++ Qualifiers and Storage Classes

C++ Qualifiers and Storage Classes Qualifiers and storage class are smaller but important programming concept that helps to make the quality of a variable more accurate for using that variable within the program. In this chapter you will learn about how qualifiers are used with variables and what the roles of different storage classes in C++ are. What is a Qualifier? A qualifier is a token added to a variable which adds an extra  quality , such as specifying volatility or constant-ness to a variable. They act like an adjective for a variable. With or without a qualifier, the variable itself still occupies the same amount of memory, and each bit has the same interpretation or contribution to the state/value. Qualifiers just specify something about how it may be accessed or where it is stored. Three qualifiers are there in C++. These are: const : This is used to define that the type is constant. volatile : his is used to define that the type is volatile. mutable:  applies to non...

Syllabus

Syllabus  C Programming Tutorials C Tutorial C Introduction History of C Programming Language C Installation C Program Structure C Input and Output (I/O) C Format Specifiers Declaration & Assignments C Tokens C Identifiers C Keywords C Constants C Operators C Data Types C Variables C Preprocessors C Type Casting C Custom Header File Flow Control C Decision Making C if Statements C if-else Statements C Nested if-else Statements C else-if Statements C goto Statement C switch Statements C Loops C while loops C do while loops C for loops Functions C Functions C Function Arguments C Library Functions C Variable Scope Arrays & Strings C Arrays C Strings Pointers C Pointers C Dynamic Memory Allocation Structure & Union C Structures C Unions File I/O C File Handling C fopen C fclose C getc C putc C getw C putw C fprintf C fscanf C fgets C fputs C feof                                     ...