You are on page 1of 13

Dynamic Memory Allocation in C++

Prepared by:
Johra Muhammad Moosa
Lecturer
Department of Computer Science & Engineering
Bangladesh University of Engineering & Technology
new
 To allocate memory in C: malloc()
 C++ provides safer way
 p-var=new type;
 p-var is a pointer of type
 new returns a pointer of specified type to dynamically allocated
memory that is large enough to hold an object of type
 Cast not needed
 sizeof is not needed
 If new fails, it returns
 NULL
 Exception
 cstdlib is not needed
 Can be overloaded
new
#include<iostream>
using namespace std;
int main()
{
int *p;
p=new int;
if(!p)
cout<<"allocation error\n";
*p=110;
cout<<"*p is "<<*p<<endl;
return 0;
}
delete
 To release memory in C: free()
 C++ provides safer way
 delete p-var;
 p-var is the pointer to be released
 Calling delete with invalid pointer: crash
delete
#include<iostream>
using namespace std;
int main()
{
int *p;
p=new int;
if(!p)
cout<<"allocation error\n";
*p=110;
cout<<"*p="<<*p<<endl;
delete p;
return 0;
}
Overloading new
#include<iostream> ~samp()
using namespace std; {
class samp { cout<<"destructing...\n";
int a; }
public: };
samp() int main()
{ {
a=1; samp *p;
} p=new samp;
samp(int a) if(!p)
{ cout<<"allocation error\n";
this->a=a; cout<<"a is "<<p->get_a()<<endl;
} delete p;
int get_a() return 0;
{ }
return a;
}
More about new & delete
 Initial value
 Dynamic array
Initialization in new
#include<iostream>
using namespace std;
int main()
{
int *p;
p=new int(110);
if(!p)
cout<<"allocation error\n";
cout<<"*p is "<<*p<<endl;
return 0;
}
Initialization in new
#include<iostream> ~samp()
using namespace std; {
class samp { cout<<"destructing...\n";
int a; }
public: };
samp() int main()
{ {
a=1; samp *p;
} p=new samp(5);
samp(int a) if(!p)
{ cout<<"allocation error\n";
this->a=a; cout<<"a is "<<p->get_a()<<endl;
} delete p;
int get_a() return 0;
{ }
return a;
}
Initialization in new
#include<iostream> ~samp()
using namespace std; {
class samp { cout<<"destructing...\n";
int a; }
int b; };
public: int main()
samp(int a, int b) {
{ samp *p;
this->a=a; p=new samp(5, 6);
this->b=b; if(!p)
cout<<"allocation error\n";
} cout<<"a, b= "<<p->get_a()<<", “
int get_a() <<p->get_b()<<endl;
{ delete p;
return a; return 0;
} }
int get_b()
{
return b;
}
Array using new
 One dimensional array
 p-var=new type[size];
 p-var points to the first element of the array
 Initialization is not possible
 So need default constructor
Array using delete
 One dimensional array
 delete[] p-var;
 Calls destructor for each element of the array
Array using new & delete
#include<iostream> int main()
using namespace std; {
class samp { samp *p;
int a; p=new samp[8];
int b; if(!p)
public: cout<<"allocation
void set(int a, int b) error\n";
{ for(int i=0; i<8; i++)
this->a=a; p[i].set(i, i+1);
this->b=b; delete[] p;
return 0;
} }
~samp()
{

cout<<"destructing...\n"
;
}
};

You might also like