title: Dynamic memory array / program crashing
body: <p>my program is using dynamic memory arrays and has functions enqueue (add at beginning and shift right) and dequeue (remove last) Show array etc. The code seems fine to me. But there is a problem when you run the program it crashes like 5 out of 10 times. I suppose it is because of wrong new / delete usage. Can someone please tell my why the program is crashing? And how to fix it?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;cstdlib&gt;
  #include &lt;stdlib.h&gt;
  
  using namespace std;
  
  template &lt;class T&gt;
  class Queue
  {
  public:
  
      Queue(int size);
      int add_value(T);
      void show_array();
      void enqueue(T);
      T dequeue();
  
  private:
  
      T *temp;
      T *data;
      int size;
      int index;
  };
  template&lt;class T&gt;
  Queue&lt;T&gt;::Queue(int s)
  {
      data = new T[s];
      if (data == NULL)
      {
          cout &lt;&lt; "Not enough memory, program ends." &lt;&lt; endl;
          exit(1);
      }
      size = s;
      index = 0;
  }
  template&lt;class T&gt;
  void Queue&lt;T&gt;::show_array()
  {
      for (int i = 0; i &lt; index; i++)
          cout &lt;&lt; data[i] &lt;&lt; ' ';
  
      cout &lt;&lt; endl;
  }
  template&lt;class T&gt;
  int Queue&lt;T&gt;::add_value(T value)
  {
      if (index == size)
      return(1);
      else
      {
        data[index] = value;
        index++;
        return(0);
      }
  }
  template &lt;class T&gt;
  void Queue&lt;T&gt;::enqueue(T X)
  {
      for(int i = size; i &gt; 0; i--)
      {
         data[i] = data[i-1];
      }
      data[0] = X;
  }
  template &lt;class T&gt;
  T Queue&lt;T&gt;::dequeue()
  {
      size -= 1;
      index -= 1;
      temp = new T[size];
      for (int i=0; i&lt;size; i++)
          temp[i] = data[i];
  
      delete[] data;
  
      data = new T[size];
      data = temp;
  
      return * data;
  }
  int main()
  {
      Queue&lt;double&gt;numbers(10);
  
      for (int i = 0; i &lt; 10; i++)
        numbers.add_value(i);
  
      cout &lt;&lt; "Array:" &lt;&lt; endl;
      numbers.show_array();
      numbers.enqueue(9.2);
      numbers.enqueue(9.1);
      cout &lt;&lt; endl;
      cout &lt;&lt; "Array after enqueue:" &lt;&lt; endl;
      numbers.show_array();
      cout &lt;&lt; "Array after dequeue:" &lt;&lt; endl;
      numbers.dequeue();
      numbers.dequeue();
      numbers.show_array();
  
      system("pause");
      return 0;
  } 
  </code></pre>