C++ Sample Program for Allocating, using, and deleting pointers.

By: Henry Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

You allocate memory on the free store in C++ by using the new keyword. new is followed by the type of the object that you want to allocate so that the compiler knows how much memory is required. Therefore, new unsigned short int allocates two bytes in the free store, and new long allocates four.

The return value from new is a memory address. It must be assigned to a pointer. To create an unsigned short on the free store, you might write

If new cannot create memory on the free store (memory is, after all, a limited resource) it returns the null pointer. You must check your pointer for null each time you request new memory.

When you are finished with your area of memory, you must call delete on the pointer. delete returns the memory to the free store. Remember that the pointer itself--as opposed to the memory to which it points--is a local variable. When the function in which it is declared returns, that pointer goes out of scope and is lost. The memory allocated with new is not freed automatically, however. That memory becomes unavailable--a situation called a memory leak. It's called a memory leak because that memory can't be recovered until the program ends. It is as though the memory has leaked out of your computer.

To restore the memory to the free store, you use the keyword delete. For example,

delete pPointer;

When you delete the pointer, what you are really doing is freeing up the memory whose address is stored in the pointer. You are saying, "Return to the free store the memory that this pointer points to." The pointer is still a pointer, and it can be reassigned. The program below demonstrates allocating a variable on the heap, using that variable, and deleting it.

Allocating, using, and deleting pointers.

1:     // 
2:     // Allocating and deleting a pointer
4:     #include <iostream.h>
5:     int main()
6:     {
7:        int localVariable = 5;
8:        int * pLocal= &localVariable;
9:        int * pHeap = new int;
10:       if (pHeap == NULL)
11:        {
12:            cout << "Error! No memory for pHeap!!";
13:            return 0;
14:        }
15:       *pHeap = 7;
16:       cout << "localVariable: " << localVariable << "\n";
17:       cout << "*pLocal: " << *pLocal << "\n";
18:       cout << "*pHeap: " << *pHeap << "\n";
19:       delete pHeap;
20:       pHeap = new int;
21:       if (pHeap == NULL)
22:       {
23:            cout << "Error! No memory for pHeap!!";
24:            return 0;
25:       }
26:       *pHeap = 9;
27:       cout << "*pHeap: " << *pHeap << "\n";
28:       delete pHeap;
29:       return 0;
30: }

Output: localVariable: 5
*pLocal: 5
*pHeap: 7
*pHeap: 9

Analysis: Line 7 declares and initializes a local variable. Line 8 declares and initializes a pointer with the address of the local variable. Line 9 declares another pointer but initializes it with the result obtained from calling new int. This allocates space on the free store for an int. Line 10 verifies that memory was allocated and the pointer is valid (not null). If no memory can be allocated, the pointer is null and an error message is printed.
To keep things simple, this error checking often won't be reproduced in future programs, but you must include some sort of error checking in your own programs.

Line 15 assigns the value 7 to the newly allocated memory. Line 16 prints the value of the local variable, and line 17 prints the value pointed to by pLocal. As expected, these are the same. Line 19 prints the value pointed to by pHeap. It shows that the value assigned in line 15 is, in fact, accessible.

In line 19, the memory allocated in line 9 is returned to the free store by a call to delete. This frees the memory and disassociates the pointer from that memory. pHeap is now free to point to other memory. It is reassigned in lines 20 and 26, and line 27 prints the result. Line 28 restores that memory to the free store.

Although line 28 is redundant (the end of the program would have returned that memory) it is a good idea to free this memory explicitly. If the program changes or is extended, it will be beneficial that this step was already taken care of.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


Be the first one to add a comment

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Henry
Generating Your Key Pair example using keytool in Java
Summary of Operators in Java
JDBC Basics and JDBC Components
The IterationTag Interface in JSP
Trigonometric, Hyperbolic, Exponential and Logarithmic Functions in C
Using Bit-field in C
Java Beans and the Expression Language
Initialization of Variables in C
Creating Struts Modules
else if statement in C
Line Counting sample program in C
Accessing Context Data in Beans using JSF
Using peek() and putback() with cin in C++
Internationalization Support in J2ME MIDP
java.lang.SecurityException: MIDP lifecycle does not support system exit.

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Constructors and Destructors in C++
Dot (.) vs Arrow (->) to access data members in C++
ctime() sample program in C++
strlen() sample program in C++
virtual inheritance example in C++
Using Comments in a C++ Program
Using functions in C++
class keyword in C++
Using switch Statements in C++
C++ Sample Program for Allocating, using, and deleting pointers.
Getting User Input Using cin in C++
Using peek() and putback() with cin in C++
Using command-line arguments in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Most Emailed Articles (in C++)
const Member Functions in C++
Tutorial on Inline Implementation in C++
Multiple statements in for loops in C++
A Brief History of C++
Difference between Procedural, Structured, and Object-Oriented Programming
C++ and Object-Oriented Programming
Getting Started with C++
Using cout in C++
Using Comments in a C++ Program
Using functions in C++
How to use Enumerated constants in C++
Demonstration of Prefix and Postfix operators in C++
The if Statement in C++
Advanced if Statements in C++
Use of Conditional (Ternary) Operator in C++