C++ Sample Program for Allocating, using, and deleting pointers.
By: Henry in C++ Tutorials on 2007-09-14
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 3: 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.
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++
Comments