Code About Us Tutorial


  Pointers and References
    What are Pointers?
    Declaring Pointers
    The Indirection and Dereference operator
    What is a Reference?
    Using References
    Using Pointers and References
    The new Keyword
    The delete Keyword
    Passing By Reference
    Passing by Value


   
 

Home > Pointers and References > The delete Keyword

November 30, 2009 4:22 pm

   

The delete Keyword

If you didn’t use the new keyword and just wrote:

 

 
Double *n;
*n = 435.3;

you would get an error because n is not initialized, it isn’t pointing to any space in memory. You could get around this if you assigned n an address of another variable. Like this:

 

 
double num;
double *pnum = #
*num = 34.0

Lets got back to the above code,

 

 
double *n = new double;
*n = 435.3;

If for some odd reason you run out of memory and you can’t create memory for the pointer, it returns the null pointer. You must check your pointer for null each time you request new memory.

Here is a good way to check to see if a pointer is null or not before assigning it a value.

 

 
#include <iostream.h>
#include <stdlib.h>

int main() {

double *n = new double; if(n==0) exit(0); //out of memory else *n = 435.3;

cout <<"value of *n: " << *n << endl;

return 0; }

This simple program checks to see if the pointer is equal to 0, if it is, it will exit, if it isn’t then it will assign the pointer a value.

Once you create a pointer it is a good idea to delete the pointer. You will do this by using the delete operator. The delete operator returns allocated memory to the freestore. You should only use the delete keyword if you created a pointer using the new keyword. Once you delete a pointer, always set it to 0, because if you call delete on a pointer that isn’t set to 0, it will crash your program.

 

 
float *Pi = new float;	//creates room for 1 float on freestore
*Pi = 3.141592;		//assigns a value
delete Pi;			//freeing memory
Pi = 0;		//now you can use the pointer again with no errors

If you don’t delete the pointer, you will get a memory leak. I’ll give you an example of a memory leak.

 

 
int *pAge = new int;
*pAge = 40;
pAge = new int;
*pAge = 20;

· the first line creates room for the new pointer in freestore, · then on the second line it assigns it a value of 40. · the third line reassigns the pointer to another spot in memory and then · the forth line assigns it a new value. This makes the first value the pointer held lost. The way to fix this is to write the following:

 

 
int *pAge = new int;
*pAge = 40;
delete pAge;		//fixes problem
pAge =0;

pAge = new int; *pAge = 20;

Please Rate this Code:


    Comments for: The delete Keyword
  There are NO user contributed comments for The delete Keyword.



Add Comment:
Name:
Email:


 «