Dynamic memory Allocation ( new , delete)
· The technique by which a program can obtain storage space in the main memory at run time is
called dynamic allocations.
· In this method , the space for the program is allocated from the free space during the execution
of the program.
· Operators new and delete that can be used for acheving dynamic memory allocation and
deallocation , respectively.
THE new AND delete OPERATORS
· The new operator not only creates an object but also allocated memory.
· The new operator allocates memory from the heap that is also called a free store.
· The object created and the memory allocated by using the new operator should be deleted and
memory should be released by the delete operator , otherwise , such a mimatch operation may
corrupt the heap or may crash the system, accroding to the ANSI standard.
· The delete operator not only destroy not only destroys objects but also releases allocated
memory.
· The new operator creates an objects , and it remains in the memory until it is released using the
delete operator. Sometimes, the object deleted using the delete operator remains in the
memory.
· If we send a null pointer to the delete operator, it is secure. Using delete to zero has no result.
· The statement delete X does not destroy the pointer X, it destroys the objecct associated with it.
· Do not apply C function such as malloc() , realloc() , or free() with new and delete operators .
These functions are until for object - orinted techniques
· Do not destroy the pointer repetitively or more than once. First time , the object is destroyed
and memory is released . If second time the same object is deleted , the object is sent to the
destroy the object and release the system resources.
· If the object created is not deleted. It occupies the memory unncessarily . It is good habit to
destroy the object and release the system resources.
new malloc()
creates objects Allocated memory
returns pointer or relevant type Returns void pointer
It is possible to overload a new op malloc() cannot be overloaded
#include<iostream.h>
#include<conio.h>
void main()
clrscr();
int i,*p;
p=&i;
p=new int[3];
*p=2;
*(p+1)=3;
*(p+2)=4;
cout<<"\n Value address:";
for(int x=0;x<3;x++)
cout<<"\n "<<*(p+x)<<"\t"<<(unsigned)(p+x);
delete []p;
getch();
output
value addres
2 3350
3 3352
4 3354