title: Using memcpy to copy the content of a dynamic array onto another produces a runtime error
body: <p>So I am trying to create a stack with a dynamic size, meaning that the capacity of the stack will change dynamically as needed. The concept worked out flawlessly in my head, create a function name <code>memoryManagement(int i)</code> that takes the size of data currently stored in the stack by a variable called <code>usedCapacity</code>. After this, the program was supposed to create a new array, use <code>memcpy</code> to copy the contents of the old array onto the new one. And finally, copy the contents of the new array back onto the old one with a new capacity. However, I keep getting a runtime error when I run my program. Also, depending in where I call the <code>showStack</code> function I sometimes get thrash numbers instead of the actual values I pushed onto the stack. If anyone could point me out on what I am doing wrong, I would greatly appreciate it.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;cstdlib&gt;
  #include &lt;cstring&gt;
  
  using namespace std;
  
  class Stack
  {
  public:
      //stack functions
      Stack();
      void push(int a);
      int pop();
      int peek() const;
      void showStack();
      ~Stack();
      //memory management
      void memoryManagement(int a);
      //void setCapacity(int  );
      //void ensureCapacity(int minCapacity);
  private:
      int top;
      int * arr;
      int capacity;
      int usedCapacity;
  };
  
  //////////////////////////////////////////////////////////////////////////////////
  
  int main() {
  
      Stack calc;
      calc.push(11);
      calc.push(33);
      calc.showStack();
      calc.push(23);
      calc.push(43);
  
      return 0;
  }
  
  //////////////////////////////////////////////////////////////////////////////////
  
  Stack::Stack()
  {
      top = -1;
      usedCapacity = 0;
      capacity = 1;
      arr = new int[capacity];
  }
  
  void Stack::push(int a)
  {
      if (top &gt; capacity)
          throw "Stack overflow";
      top++;
      usedCapacity++;
      arr[top] = a;
      memoryManagement(usedCapacity);
  }
  
  int Stack::pop()
  {
      if (top &lt;= -1)
          throw "Stack underflow";
          arr[--top];
  }
  
  int Stack::peek() const
  {
      return top;
  }
  
  void Stack::showStack()
  {
      for (int i = 0; i &lt; capacity; i++)
      {
          cout &lt;&lt; arr[i] &lt;&lt; " ";
      }
      cout &lt;&lt; endl;
  }
  
  Stack::~Stack()
  {
      delete[] arr;
  }
  
  void Stack::memoryManagement(int a)
  {
      if (a &gt;= capacity)
      {
          int newCapacity;
          newCapacity = (a * 3) / 2 + 1;
  
          int * arr2 = new int[newCapacity];
          memcpy(arr2, arr, sizeof(int) * usedCapacity);
  
          delete[] arr;
          arr = arr2;
          delete[] arr2;
      }
  }
  </code></pre>