// dynamic memory allocation
// ex9: allocate in one function and delete in another function
// 2 ERRORS:
/****
1. memory leak - where you allocate memory on the heap and then lose the address of the memory.
Solution:
make sure every new is paired with a delete

2. dangling pointer - pointer that is pointing to memory that has already been freed up.  
Solution:
Set a pointer to NULL (0) when you delete its memory
****/

#include <iostream>
using namespace std;

int* funcallocate();

int main()
{
 int* newmem;

 newmem = funcallocate();
 
 delete[] newmem;
 newmem=NULL; // sets the ptr to 0 so that its not dangling

 return 0;
}

int* funcallocate()
{
  int numelts;
  // new operator  returns a pointer
  int *myarray;

  cout << "enter a number of elements: ";
  cin >> numelts;

// give me an array of numelts elements of type int
try {
     myarray =  new int[numelts];
    }
// newer compilers throw and exception called bad_alloc
  catch(bad_alloc)
    {  cout << "the memory was NOT allocated!!!" << endl;
       exit(1);
    }
  return myarray;
}
