dynamic array of pointers that grow at runtime

Hi,

I can't for the life of me figure out why my application crashes after the 7th cin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

int main ()
{
   int * a = new int[0];
   int n = 0;
  //a[n] = 2; 
   while (1){
      cin >> a[n];
      if (cin.fail())
      {
         cout << "failed!";
      }
      if (a[n] == -1) break;
      n++;
      int * tmp = new int[n];
      for (int i = 0; i<n;i++)
         tmp[i] = a[i];
      delete [] a;
      a = 0;
      a = tmp;

   }
   for(int u = 0; u < n; u++)
        cout << a[u] << ",";
   cout << endl;
   delete []a;

   return 0;
}


It crashes with the following error:

 
*** Error in `./ptr': free(): invalid next size (fast): 0x0000000001af6010 *** 


I'm using gcc as my compiler.

Here's an interesting bit, when I execute the application with valgrind it does not crash. valgrind gives me an all memory deallocated message, so that leaves me to think that there is no dereference data lingering out there.

Any pointers will be appreciated.
Topic archived. No new replies allowed.