0% found this document useful (0 votes)
36 views28 pages

Dynamic Memory Allocation

Uploaded by

bhaveshtanwar693
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views28 pages

Dynamic Memory Allocation

Uploaded by

bhaveshtanwar693
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

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)
• 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

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

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

 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
10-4
• delete[] <pointer_name>//For de-allocating array of memory locations
Memory allocation failure
• Memory allocation failure may happen in a situation when system is unable to allocate
sufficient amount of memory which has been requested at run time(or during dynamic
memory allocation)
• When this happens, new operator will assign NULL to the pointer, turning it into NULL
pointer, which clearly suggest, system was unable to allocate requested memory
• We can check this situation using following lines of code:
<data_type> *p=new data_type;
Or
<data_type>*p=new data_type[size];
// Here p is a pointer(it could be any variable)
if(!p)
{
cout<<"\n Memory allocation failure";
exit(1);
}
//or
if(p==NULL)
{
cout<<"\n Memory allocation failure";
exit(1);
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);
}
return 0;
}
Basic program using new and delete
Program to allocate/deallocate one memory location
#include<iostream>
#include<stdlib.h>
using namespace std;
int main(){
int *p=NULL;
p=new int;
if(p==NULL)
{cout<<"\n Memory allocation failure";
exit(1);}
else{
cout<<"\nMemory allocated";
*p=12;
cout<<"Integer value stored is:"<<*p;
delete p;//Deallocation of memory
cout<<"\n Memory deallocated";
}
return 0;
Example program WAP to calculate simple interest
using DMA
#include<iostream>
#include<stdlib.h> *si=(0.01)*(*p)*(*r)*(*t);
using namespace std;
int main()
cout<<"\n Simple interest
{ is:"<<*si;
float *p=NULL;
float *r=NULL; delete p;
float *t=NULL;
float *si=NULL; delete r;
p=new float;
r=new float; delete t;
t=new float;
si=new float; delete si;
if(p==NULL||r==NULL||t==NULL||si==NULL)
{ return 0;
cout<<"\n Memory allocation failure";
exit(1); }
}
cout<<"\n Enter principle,rate and time:";
cin>>*p>>*r>>*t;
Program to allocate/deallocate array of memory locations

#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

• A destructor is a member function of a class, which gets called


when the object goes out of scope". This means all clean ups
and final steps of class destruction are to be done in destructor.
• The order of execution of destructor in an inherited class during
a clean up 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
Program—Non-virtual base destructor(Problem Derived class destructor not
getting called)
#include<iostream>
using namespace std;

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)

You might also like