Advertisement
Caminhoneiro

Dinamic allocate memory

Apr 20th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. #include "stdafx.h"
  2. // Heap
  3. // Demonstrates dynamically allocating memory
  4. #include <iostream>
  5. using namespace std;
  6. int* intOnHeap(); //returns an int on the heap
  7. void leak1(); //creates a memory leak
  8. void leak2(); //creates another memory leak
  9. int main()
  10. {
  11.     int* pHeap = new int;   //allocates memory on the heap and returns its address.
  12.     *pHeap = 10; //Receive the value
  13.     cout << "*pHeap: " << *pHeap << "\n\n"; //Debug the value if I use cout << pHeap it will debug the address
  14.     cout << "pHeap: " << pHeap << "\n\n";
  15.     int* pHeap2 = intOnHeap();
  16.     cout << "*pHeap2: " << *pHeap2 << "\n\n";
  17.     cout << "Freeing memory pointed to by pHeap.\n\n";
  18.     delete pHeap;
  19.     cout << "Freeing memory pointed to by pHeap2.\n\n";
  20.     delete pHeap2;
  21.     //get rid of dangling pointers
  22.     pHeap = 0;
  23.     pHeap2 = 0;
  24.     return 0;
  25. }
  26. int* intOnHeap()
  27. {
  28.     int* pTemp = new int(20);
  29.     return pTemp;
  30. }
  31. //Examples of how not allocate memory (causes leak)
  32. void leak1()
  33. {
  34.     int* drip1 = new int(30);
  35. }
  36. void leak2()
  37. {
  38.     int* drip2 = new int(50);
  39.     drip2 = new int(100);
  40.     delete drip2;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement