#include<iostream.h>
#include<conio.h>
class A
{
public:
A()
{
cout<<"C-A"<<endl;
}
void show()
{
cout<<"Show"<<endl;
}
~A()
{
cout<<"D-A"<<endl;
}
};
int main()
{
clrscr();
{
int *a=new int(5);
cout<<*a<<endl;
int *A=new int[5];
A[0]=6;
cout<<A[0]<<endl;
/*for(int i=0;i<5;i++)
{
cin>>A[i];
}
for(i=0;i<5;i++)
cout<<A[i]; */
delete a;
cout<<*a<<endl;
delete[] A;
//delete A[1]; Error
delete [1]A;
cout<<A[0]<<endl;
}
getch();
return 0;
}
delete operator
Compiler did not automatically deallocate dynamically allocated memory, If we want to delete dynamically allocated memory, we must deallocate it manually using delete operator.
Syntax:
// Release memory pointed by pointer-variable
delete pointer-variable;
For example
int *p=new int;
//dynamically allocated memory
int *q = new int(5);
//dynamically allocated memory
delete p;
//dynamically deallocated memory
delete q;
//dynamically deallocated memory
The delete operator deallocates memory and calls the destructor for a single object created with new.
delete []
To free the dynamically allocated array pointed by pointer-variable, use following form of delete:
// Release block of memory pointed by pointer-variable
delete[] pointer-variable;
Example:
// It will free the entire array pointed by p.
delete[] p;
for example
int *p = new int[5];
delete [] p;
or
delete [size] p;
delete [5] p;
We can use any value for size. It will delete the
entire array. but delete [size] p is not working in many compiler. So always use delete [] p; without size.
1. The delete [] operator deallocates memory and calls destructors for an array of objects created with new [].
2. The delete[] operator is used to delete arrays. The delete operator is used to delete non-array objects.
3. delete is used to de-allocate memory allocated for single object
4. delete[] is used to de-allocate memory allocated for array of objects
Deleting the array just tells the heap manager that that area of memory once again available for use in the future. It doesn't immediately overwrite the memory. It does, however, mean that the area might get overwritten at any time. So you aren't allowed to rely on its contents anymore. Content of array may be same as before the delete operator and after the delete operator. The memory is free, which means it isn't attributed anymore, but the compiler's not going to take the extra effort to wipe it back to 0 every time something's deleted.
Default value of elements in dynamically allocated array
is 0.
No comments:
Post a Comment