home *** CD-ROM | disk | FTP | other *** search
/ Beginning C++ Through Gam…rogramming (2nd Edition) / BCGP2E.ISO / source / chapter09 / heap.cpp < prev   
Encoding:
C/C++ Source or Header  |  2006-10-25  |  929 b   |  52 lines

  1. // Heap
  2. // Demonstrates dynamically allocating memory
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. int* intOnHeap();  //returns an int on the heap
  9. void leak1();      //creates a memory leak
  10. void leak2();      //creates another memory leak
  11.  
  12. int main()
  13. {
  14.     int* pHeap = new int;
  15.     *pHeap = 10;
  16.     cout << "*pHeap: " << *pHeap << "\n\n";
  17.     
  18.     int* pHeap2 = intOnHeap();
  19.     cout << "*pHeap2: " << *pHeap2 << "\n\n";
  20.     
  21.     cout << "Freeing memory pointed to by pHeap.\n\n";
  22.     delete pHeap;
  23.  
  24.     cout << "Freeing memory pointed to by pHeap2.\n\n";
  25.     delete pHeap2;
  26.     
  27.     //get rid of dangling pointers
  28.     pHeap = 0; 
  29.     pHeap2 = 0;
  30.    
  31.     return 0;
  32. }
  33.  
  34. int* intOnHeap()
  35. {
  36.     int* pTemp = new int(20);
  37.     return pTemp;
  38. }
  39.  
  40. void leak1()
  41. {
  42.     int* drip1 = new int(30);
  43. }
  44.  
  45. void leak2()
  46. {
  47.     int* drip2 = new int(50);
  48.     drip2 = new int(100);
  49.     delete drip2;
  50. }
  51.  
  52.