I am trying to write a very simple piece of code to create a 3×2 matrix using STL vectors.
This is what I have:
#include <vector>
using namespace std;
int main ()
{
int i;
vector<int> * x = new vector<int> [3];
for (i = 0; i < 3; i++)
x[i] = vector<int> (2);
delete x;
return 0;
}
The problem is that every time I run the program, it crashes. If I remove the delete x then it works fine, but will probably result in memory leaks.
I know that this is probably not the best way to create a matrix and there is a battalion of choices out there, but I would just like to know why the above program crashes every time.
Also, replacing every occurrence of vector<int> with say int, then all work fine again.
To destroy dynamically allocated arrays you must use
delete[], notdelete.While that will make the code work, it is a suboptimal solution. The following program does the same thing, but is much more succint, and safer.