Dynamic Memory Allocation
Dynamic Memory Allocation
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)
• 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
•
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
#include<iostream>
#include<stdlib.h>
using namespace std; cout<<"\n Entered elements
int main(){ are:";
int *arr;
for(int i=0;i<size;i++)
int size;
cout<<"\n Enter the size of integer array:"; {
cin>>size; cout<<"\n"<<*(arr+i);
cout<<"\n Creating an array of size"<<size;
arr=new int[size];
}
if(arr==NULL){ }
cout<<"\n Problem in memory allocation"; delete []arr;
exit(1);
}
cout<<"\nMemory
else{ deallocated";
cout<<"\n Dynamic allocation of memory for array return 0;
arr is successful.";
cout<<"\n Enter the array elements:"; }
for(int i=0;i<size;i++)
Program to find the sum and average of double typed array elements using DMA
#include<iostream>
#include<stdlib.h>
for(int i=0;i<size;i++)
using namespace std; {
int main()
{ *sum=*sum+arr[i];
double *arr,*sum,*avg;
int size;
}
sum=new double; cout<<"\n Sum of elements of
avg=new double;
cout<<"\n Enter the size of double array:";
array is:"<<*sum;
cin>>size; *avg=*sum/size;
cout<<"\n Creating an array of size"<<size;
arr=new double[size]; cout<<"\n Average of array
if(arr==NULL||sum==NULL||avg==NULL) elements is:"<<*avg;
{
cout<<"\n Problem in memory allocation"; delete []arr;
exit(1);
}
delete sum;
cout<<"\nEnter array elements:"; delete avg;
for(int i=0;i<size;i++)
{ return 0;
cin>>arr[i];
}
}
Program to find the sum of array elements using DMA
#include<iostream> for(int i=0;i<size;i++)
#include<stdlib.h>
using namespace std; {
int main() sum=sum+arr[i];
{
int *arr,sum=0;
//sum=sum+*(arr+i);//Possible to
int size; use pointer to array for sum
cout<<"\n Enter the size of integer array:"; }
cin>>size;
cout<<"\n Creating an array of size"<<size; cout<<"\n Sum of elements of array
arr=new int[size]; is:"<<sum;
if(arr==NULL) delete []arr;
{
cout<<"\n Problem in memory allocation"; return 0;
exit(1); }
}
cout<<"\nEnter array elements:";
for(int i=0;i<size;i++)
{
cin>>arr[i];
//cin>>*(arr+i);//Possible to take input using Pointer
to array
//cin>>*(i+arr);
}
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.
12
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;
}
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;
}
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)
15
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)
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;
return 0;
}
Dynamic memory allocation inside a class-
#include<iostream> Program Example
using namespace std; void display_data(){
class Array for(int i=0;i<size;i++)
{
{
int *arr;
cout<<"\t"<<arr[i];
int size;
public:
}
void get_data(int n) cout<<"\n Sum of elements="<<get_sum();
{ }
size=n; ~Array(){
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 n;
int sum=0;
for(int i=0;i<size;i++)
cout<<"\n Enter the number of
elements:"<<endl;
{
sum+=arr[i]; cin>>n;
} a.get_data(n);
return sum; a.display_data();
} return 0;
Dynamic memory allocation inside a
class-Allocating/deallocationg dynamic memory to string
#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: void display() //display the String
char* str; //pointer to string {
public: cout << str << endl;
string1(char* s) //constructor, one arg
}
{
};
int length = strlen(s); //length of string argument
int main()
str = new char[length+1]; //get memory
{ //uses 1-arg constructor
strcpy(str, s); //copy argument to it
string1 s1("This is DMA example for
}
string");
cout << "s1="; //display string
s1.display();
return 0;
}
Allocating dynamic memory to object of a class(or array of objects)
int main(){
#include<iostream>
int n;
#include<stdlib.h>
cout<<"\n Enter number of
#include<stdio.h>
employees:";
using namespace std;
cin>>n;
class Employee{
Employee *p=new Employee[n];
int id;
float salary;
Employee *d=p;
public: Employee *flag=p;
void input(){ if(p==NULL){
cout<<"\n Enter id:"; cout<<"\n Memory allocation failure";
cin>>id; Exit(1);}
cout<<"\n Enter salary:"; for(int i=0;i<n;i++){
cin>>salary;} p->input();
void display(){ p++;}
cout<<"\n"<<id<<" "<<salary; for(int i=0;i<n;i++){
} d->display();
};
d++;}
Allocating dynamic memory to object-new operator invokes
constructor of a class along with allocating dynamic memory to
object(or array of objects)
#include <iostream>
using namespace std; Output:
class sample {
public: Enter no. of
sample() {
cout << "Constructor called" <<endl; objects:
}
~sample() { 2
cout << "Destructor called" <<endl;
} Constructor called
};
int main() { Constructor called
int n;
cout<<"\n Enter no. of objects:"; Destructor called
cin>>n;
sample* obj1 = new sample[n];//Array of objects
delete [] obj1
Destructor called
return 0;
• }
Dynamic constructors
If we allocate dynamic memory inside the definition of any type of constructor(Default/Parameterized) using
new/malloc()/calloc() then that type of constructor is known as Dynamic constructor
By using this constructor, we can dynamically initialize the objects of the class.
Example1:
#include <iostream>
using namespace std;
class example1 {
const char* ptr;
public:
// default constructor
example1()
{
// allocating memory at run time
ptr = new char[8];
ptr = "Dynamic";
}
void show()
{
cout << ptr << endl;
}
};
int main()
{
example1 *ptr = new example1();
ptr->show();
Dynamic constructor-Program example 2
#include<iostream>
for(int i=0;i<n;i++)
using namespace std; {
class Array cin>>arr[i];
}
{
}
private: void Array::show_data()
int *arr; {
for(int i=0;i<n;i++)
int n;
{
public: cout<<" "<<arr[i];
Array(); }
}
void show_data();
int main()
}; {
Array::Array() int no_object;
cout<<"\n Enter no. of objects:";
{
cin>>no_object;
cout<<"\nEnter size:"; Array *ptr=new Array[no_object];
cin>>n; for(int i=0;i<no_object;i++)
{
arr=new int[n];
ptr->show_data();
cout<<"\n Enter the elements:"; ptr++;
}
return 0;
}
Virtual Destructor
class base {
public:
Output:
base()
{ cout<<"Constructing base \n"; }
~base()
Constructing
base
{ cout<<"Destructing base \n"; }
};
Constructing
class derived1: public base {
public:
derived1()
{ cout<<"Constructing derived \n"; }
~derived1() derived
{ cout<<"Destructing derived \n"; }
};
int main() Destructing base
{
base *b = new derived1;
delete b;
return 0;
Program--Virtual destructor(Solution to the problem stated in
previous program)
#include<iostream>
using namespace std; Output:
class base { Constructing base
public:
Constructing derived
base()
{ cout<<"Constructing base \n"; } Destructing derived
virtual ~base() Destructing base
{ cout<<"Destructing base \n"; }
};
class derived1: public base {
public:
derived1()
{ cout<<"Constructing derived \n"; }
~derived1()
{ cout<<"Destructing derived \n"; }
};
int main()
{
base *b = new derived1;
delete b;
return 0;
}
new vs malloc()
new vs malloc()(more points)