Dynamic Memory Allocation
Dynamic Memory Allocation
1
Table of Contents
• Allocation of Memory(Types of memory allocation)
• Dynamic Memory Allocation(Syntax of new and delete)
• Memory allocation failure(Concept and Program example)
• Basic programs using new and delete(Single memory and array
of memory locations)
• Memory leak(Concept, Program example along with solution)
• Dangling pointer(Concept, Program example along with
solution)
• Allocating dynamic memory to object(or array of objects)
• Program example where new is invoking constructor of the
class
• Dynamic constructor(Concept and Program example)
• Virtual Destructor( Concept and Program example)
2
• Difference between new and malloc()
Allocation of Memory
Static(or compile time memory) Allocation:
• Allocation of memory space at compile time, e.g. int a, int a[12];
• During compile time memory allocation, fixed amount of memory
is reserved, which cannot be changed during execution.
• Hence, if there is a change in the memory requirement, that cannot
be accommodated.
• Consequences could be: memory could be wasted(or under utilized)
and if extra memory is required, then it cannot be allocated
• Allocated from stack
3
Allocation of Memory
Dynamic( or run time memory)Allocation:
• Allocation/de-allocation of memory space at run time(with the
help of new and delete operators)
• This concept will help to allocate only that much of memory
which is actually required by the program during run time,
hence there will no memory wasted and sufficient amount of
memory will be allocated, hence avoiding the consequences of
compile time memory allocation.
• Allocated from heap
4
Dynamic Memory Allocation
• Dynamic memory allocation/de-allocation can be done with the help
of new and delete operators
• General syntax for allocation could be:
<data_type> *<ptr_name>=new <data_type>;
//For one memory location
or
<data type> *<ptr_name>= new <data_type>[size];
//For array of memory locations
Example:
int *ptr=new int;
Here data type: int, denotes, we want to allocate memory for storing one
integer value.
int *ptr=new int[10];//Memory for 10 integer values will be reserved
10-5
Total memory allocation using dynamic
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch;
cout<<sizeof(ch)<<endl;
char *c;
cout<<sizeof(c);
}
6
Dynamic Memory Allocation
new returns address of memory location , which will be taken
by ptr(pointer)
If compiler is unable to allocate memory, then NULL will be
returned.
General syntax for de-allocation of memory:
• delete <pointer_name>// For de-allocating single memory
location
• delete[] <pointer_name>//For de-allocating array of memory
locations
7
Static Vs. dynamic memory allocation
#include <iostream> #include <iostream>
#include <string> #include <string>
using namespace std;
using namespace std;
int main()
int main() {
{ int n;
int arr[5]; cin>>n;
cout<<"enter array int *arr=new int[n];
elements"; cout<<"enter array elements";
for(int i=1;i<=5;i++) for(int i=1;i<=n;i++)
{ {
cin>>arr[i]; cin>>*(arr+i);
} }
} }
8
Memory allocation failure
• Memory allocation failure may
happen in a situation when <data_type> *p=new data_type;
Or
system is unable to allocate
<data_type>*p=new data_type[size];
sufficient amount of memory // Here p is a pointer(it could be any
which has been requested at run variable)
time(or during dynamic memory if(!p)
allocation) {
• When this happens, new operator cout<<"\n Memory allocation failure";
will assign NULL to the pointer, exit(1);
}
turning it into NULL pointer,
//or
which clearly suggest, system if(p==NULL)
was unable to allocate requested {
memory cout<<"\n Memory allocation failure";
• We can check this situation using exit(1);
following lines of code: }
9
Memory allocation failure—Program example
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int *p=NULL;
p=new int;
/*if(!p)
{
cout<<"\n Memory allocation failure";
exit(1);
}*/
if(p==NULL)
{
cout<<"\n Memory allocation failure";
exit(1);
}
}
10
Allocate/deallocate one memory location
if(p==NULL)
#include<iostream> {
using namespace std; cout<<"\n Memory allocation failure";
int main() exit(1);
{ }
else
int *p=NULL;
{
p=new int; cout<<"Memory allocated“<<endl;
/*if(!p) *p=12;
{ cout<<"Integer value stored
cout<<"\n Memory allocation is:"<<*p<<endl;
delete p;//Deallocation of memory
failure";
cout<<"\n Memory deallocated“<<endl;
exit(1); }
}*/ }
11
WAP to calculate simple interest using DMA
#include<iostream> if(p==NULL||r==NULL||t==NULL||
si==NULL)
#include<stdlib.h>
{
using namespace std; cout<<"\n Memory allocation failure";
int main() exit(1);
{ }
cout<<"\n Enter principle,rate and time:";
float *p=NULL;
cin>>*p>>*r>>*t;
float *r=NULL; *si=(0.01)*(*p)*(*r)*(*t);
float *t=NULL; cout<<"\n Simple interest is:"<<*si;
float *si=NULL; delete p;
p=new float; delete r;
delete t;
r=new float;
delete si;
t=new float; return 0;
si=new float; }
12
WAP to calculate factorial of given number
using DMA
13
#include<iostream>
#include<stdlib.h>
using namespace std;
int main() cout<<"\n Factorial is:"<<*fact;
delete p;
{
delete fact;
int *fact=NULL; return 0;
int *p=NULL; }
p=new int;
fact=new int;
if(p==NULL||fact==NULL)
{
cout<<"\n Memory allocation failure";
exit(1);
}
cout<<"\n Enter the number:";
cin>>*p;
*fact=1;
for(int i=1;i<=*p;i++)
{
*fact=*fact*i; 14
}
Program to allocate/deallocate array of memory locations
16
#include<iostream>
#include<stdlib.h>
using namespace std; for(int i=0;i<size;i++)
int main(){ {
double *arr,*sum,*avg;
*sum=*sum+arr[i];
int size;
}
sum=new double;
avg=new double; cout<<"\n Sum of elements of array
cout<<"\n Enter the size of double array:";
is:"<<*sum;
cin>>size; *avg=*sum/size;
cout<<"\n Creating an array of size"<<size; cout<<"\n Average of array elements
arr=new double[size]; is:"<<*avg;
if(arr==NULL||sum==NULL||avg==NULL){ delete []arr;
cout<<"\n Problem in memory allocation"; delete sum;
exit(1);} delete avg;
cout<<"\nEnter array elements:"; return 0;
for(int i=0;i<size;i++){
}
cin>>arr[i];
} 17
Program to find the sum of array elements
using DMA
18
#include<iostream> cout<<"\nEnter array elements:";
#include<stdlib.h> for(int i=0;i<size;i++)
using namespace std; {
int main() cin>>arr[i];
{ //cin>>*(arr+i);//Possible to take
int *arr,sum=0; input using Pointer to array
int size; //cin>>*(i+arr);
cout<<"\n Enter the size of integer }
array:";
cin>>size; for(int i=0;i<size;i++)
cout<<"\n Creating an array of {
size"<<size; sum=sum+arr[i];
arr=new int[size]; //sum=sum+*(arr+i);//Possible to use
if(arr==NULL) pointer to array for sum
{ }
cout<<"\n Problem in memory cout<<"\n Sum of elements of array
allocation"; is:"<<sum;
exit(1);} delete []arr;} 19
WAP
• Write a program to dynamically allocate memory for three dynamic
arrays using the new operator: one for storing the user-input integers, one
for storing odd numbers from the list, and the other for storing even
numbers from the list. The program should then display separate lists of
odd and even integers. Write a program to accomplish this task.
.
• Input Format
– The first line of the input represents the size of the array.
– The second line represents the array elements, separated by a space
• Output Format
– The first line of the output displays the even integers, separated by
space.
– The second line displays the odd integers, separated by space.
20
#include <iostream>
using namespace std;
int main() { else
int n; {
cout<<"Enter value f n:"; oddArray[oddCount] = inputArray[i];
cin >> n; oddCount++;
int* inputArray = new int[n]; }}
int* oddArray = new int[n]; cout << "List of Odd Integers: ";
int* evenArray = new int[n]; for (int i = 0; i < oddCount; ++i)
{
int oddCount = 0;
cout << oddArray[i] << " ";
int evenCount = 0; }
for (int i = 0; i < n; ++i) cout << endl;
{ cout << "List of Even Integers: ";
cin >> inputArray[i]; for (int i = 0; i < evenCount; ++i)
if (inputArray[i] % 2 == 0) {
{ cout << evenArray[i] << " ";
evenArray[evenCount] = inputArray[i]; }
evenCount++; }
}
21
Memory leak
• When a programmer allocates memory dynamically(either with the
help of new/ malloc()/calloc()/realloc()) but forgets to de-allocate it
using delete/delete[]/ or free(), then memory leak situation may arise.
• In this situation, system will assume memory is still under usage,
although memory is no longer required, but as, it has not been deleted/
or de-allocated explicitly, it will be unnecessarily under usage.
• If it is keep on happening in the program, i.e. memory is allocated but
not de-allocated, then at one time, system may run out of memory and
lot of problems may arise[ Like: System crash].
• Solution: Always de-allocate /or delete the memory using delete
operator if allocated through new/ or using free() function if allocated
through malloc()/calloc(), once the task of using that memory is
completed.
22
Memory leak-Example
// Program with memory leak
#include <iostream>
using namespace std;
// function with memory leak
void mem_leak()
{
int* ptr = new int[10];
//Memory has been allocated at run time but not de-allocated, so this function
can lead to memory leak
}
int main()
{
mem_leak();
return 0;
}
23
Memory leak-Solution
// Program with memory leak
#include <iostream>
using namespace std;
// function with memory leak
void mem_leak()
{
int* ptr = new int[10];
delete [] ptr; //Solution to memory leak
}
int main()
{
mem_leak();
return 0;
}
24
Dangling Pointer
• It is a type of pointer which is pointing towards such a memory
location which has been already deleted/ or de-allocated
• So, pointer is unnecessarily pointing to a free memory, which may
depict unpredictable behavior in the later stages.
• So, it is better to assign NULL to the pointer, once the memory to
which it is pointing has been de-allocated(Solution to the dangling
pointer problem)
25
Dangling pointer example-1
When variable goes out of scope(Compile time memory allocation/de-
allocation case) with solution
#include<iostream>
using namespace std;
int main()
{
int *ptr;
{
int v=23;
ptr = &v;
cout<<"Address is(inside block):"<<ptr<<"\n";
}
// Here ptr is dangling pointer as v is no longer existing
cout<<"Address is(outside block):"<<ptr;
//ptr is dangling pointer(same address is printed)
ptr=NULL; //Solution to dangling pointer(assign null address)
cout<<"\nAddress is(outside block):"<<ptr;
}
26
Dangling pointer example-2
Memory allocation/de-allocation at runtime(or Dynamic memory allocation/de-allocation)
with solution
#include <iostream>
using namespace std;
int main ()
{
int* pvalue = NULL; // Pointer initialized with null
pvalue = new int; // Request memory for the variable
*pvalue = 23; // Store value at allocated address
cout<<"Address where pointer is pointing before deletion:"<<pvalue<<endl;
delete pvalue; // free up the memory
cout<<"Address where pointer is pointing after deletion:"<<pvalue<< endl;
//Dangling pointer(Same address will be printed)
pvalue=NULL; //pvalue is no longer a dangling pointer
cout<<"\n"<<pvalue;
27
}
DMA to string using class
#include <iostream> ~string1() //destructor
#include <string.h> //for strcpy(), etc {
using namespace std;
cout << "Deleting str\n";
class string1 //user-defined string type
{ delete[] str; //release memory
private: }
char* str; //pointer to string void display() //display the String
public: {
string1(char* s) //constructor, one arg cout << str << endl;
{ }};
int length = strlen(s); //length of string
int main()
str = new char[length]; //get memory
strcpy(str, s); //copy argument to it { //uses 1-arg constructor
} string1 s1("This is DMA example for string");
cout << "s1="; //display string
s1.display();
} 28
DMA inside a class
#include<iostream> void display_data(){
using namespace std; for(int i=0;i<size;i++){
class Array{ cout<<"\t"<<arr[i];}
int *arr; cout<<"\n Sum of
int size; elements="<<get_sum();
public: }
void get_data(int n){
~Array(){
size=n;
arr=new int[size]; delete []arr;
for(int i=0;i<size;i++){ cout<<"\nMemory deallocated";
cin>>arr[i]; }};
}} int main(){
int get_sum(){ Array a;
int sum=0; int n;
for(int i=0;i<size;i++){
cout<<"\n Enter the number of
sum=sum+arr[i];
elements:"<<endl;
}
return sum; cin>>n;
} a.get_data(n);
29
a.display_data();}
WAP
• Develop a currency converter application to convert an
amount of money from USD to the desired target currency
using a specific exchange rate using class. The application
uses dynamic memory allocation with the new and delete
operators to handle exchange rates.
• Input Format
– The first line contains the exchange rate.
– The second line contains the amount in USD.
• Output Format
– The output displays the converted amount.
30
Solution 1
#include <iostream> double convertCur()
using namespace std; {
class CurrencyCon { return (*amount) * (*exchangeRate);
private: }
double *exchangeRate; ~CurrencyCon()
double *amount; {
delete exchangeRate;
public:
delete amount;
void getdata() }
{ };
exchangeRate=new double;
amount=new double; int main() {
cout<<"Enter exchangeRate and amount:"; CurrencyCon c;
cin>>*exchangeRate>>*amount; c.getdata();
cout<<c.convertCur();
} }
31
Solution 2
double convertCur()
#include <iostream> {
using namespace std; return (*amount) * (*exchangeRate);
class CurrencyCon { }
private: ~CurrencyCon()
double *exchangeRate; {
double *amount;
delete exchangeRate;
public:
delete amount;
CurrencyCon(double Rate,double am)
}
{
};
exchangeRate=new double;
amount=new double; int main() {
*exchangeRate=Rate; double exchangerate,amount;
*amount=am; cout<<"enter values of exchange rate and
} amount";
cin>>exchangerate>>amount;
CurrencyCon c(exchangerate,amount);
32
cout<<c.convertCur(); }
DMA to object of a class
#include<iostream> int main()
#include<stdlib.h> {
#include<stdio.h> int n;
using namespace std;
cout<<"\n Enter number of
class Employee
{
employees:";
int id; cin>>n;
float salary; Employee *p=new Employee[n];
public: Employee *d=p;
void input()
{
for(int i=0;i<n;i++)
cout<<"\n Enter id:"; {
cin>>id; p->input();
cout<<"\n Enter salary:";
p++;
cin>>salary;
} }
void display() for(int i=0;i<n;i++)
{ {
cout<<"\n"<<id<<" "<<salary;
d->display();
}
}; d++;
33
}}
Dynamic constructors
34
Dynamic constructor Example 1
#include<iostream> example(int x, int y, int z)
using namespace std; {
class example num1 = x;
{ num2 = y;
int num1; ptr = new int;
int num2; *ptr = z;
int *ptr; }
public: void display(){
example() cout << num1 << " " << num2 << " " << *ptr<<endl;
{ }
num1 = 0; };
num2 = 0; int main()
ptr = new int; {
*ptr=0; example obj1;
} obj1.display();
example obj2(3, 5, 11);
obj2.display();
} 35
Dynamic
#include<iostream>
constructor Example 2
int main()
using namespace std;
class example {
{ example obj1;
char* ptr; obj1.display();
public: }
// default constructor
example()
{
// allocating memory at run time
ptr = new char[15];
ptr = "Learning c++";
}
void display()
{
cout << ptr;
}
};
36
WAP
Write a program to convert Celsius to Fahrenheit using
class. The application uses dynamic memory allocation
inside the parametrize constructor.
37
#include <iostream> ~CelToFer()
using namespace std; {
class CelToFer{ delete celcius;
private: }
double *celcius; };
public:
CelToFer(double cel)
int main() {
{
celcius=new double; double celcius;
*celcius=cel; cout<<"enter celcius";
} cin>>celcius;
double CelToFercon() CelToFer c(celcius);
{ cout<<c.CelToFercon();
return (1.8*(*celcius))+32; }
}
38
Virtual Destructor
• Destructor destroys the class objects created by the constructor.
• The order of execution of destructor in an inherited class is like this.
1. Derived class destructor
2. Base class destructor
• When object of the derived class has been allocated memory dynamically
and a base class pointer is pointing towards it, then on deleting a derived
class object using a pointer to a base class that has a non-virtual destructor
results in undefined behaviour (i.e. destructor for derived class does not
get called)
• To correct this situation, the base class should be defined with a virtual
destructor, which will make sure the derived class destructor is also called
along with base class constructor in a correct sequence.
39
Program—Non-virtual base
destructor(Problem Derived class
destructor not getting called)
40
class derived: public base
#include<iostream> {
using namespace std; public:
class base derived()
{ {
public: cout<<"Constructing derived \n";
base() }
{ ~derived()
cout<<"Constructing base \n"; {
} cout<<"Destructing derived \n"; }
~base() };
{ int main()
cout<<"Destructing base \n"; {
} base *b = new derived;
}; delete b;
}
Output:
Constructing base
Constructing derived
Destructing base 41
Program--Virtual destructor(Solution to
the problem stated in previous program)
42
#include<iostream> class derived1: public base
using namespace std; {
class base { public:
public: derived1()
{
base() cout<<"Constructing derived \n";
{ }
cout<<"Constructing base \n"; ~derived1()
} {
cout<<"Destructing derived \n";
virtual ~base()
}
{ };
cout<<"Destructing base \n"; int main()
} {
}; base *b = new derived1;
delete b;
}
Output:
Constructing base
Constructing derived
Destructing derived 43
new vs malloc()
44
new vs malloc()(more points)
45