Reputation: 3823
I am trying to write a very simple piece of code to create a 3x2 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.
Upvotes: 1
Views: 205
Reputation: 227390
You need to use delete []
, since you have a dynamically allocated array. The fact that you have vectors has nothing to do with it.
You could greatly simplify your code by using a vector<vector<int>>
:
vector<vector<int>> v(3); // holds three empty vector<int>
Or even
vector<vector<int>> v(3, std::vector<int>(2)); // holds 3 size 2 vector<int>
Upvotes: 3
Reputation: 38153
You're using "array" new
, so you need the same for delete
:
delete[] x;
//....^^
Using delete x;
here is undefined bahaviour, so anything could happen. You're lucky, that your program crashes :)
Don't do this, unless you have really good reason for this. You may have
std::vector< std::vector< int > > x;
Then your code would become:
std::vector< std::vector< int > > x( 3 );
for( unsigned int ii = 0; ii < x.size(); ++ii )
{
x[ ii ].resize( 2 );
}
Or even:
std::vector< std::vector< int > > x( 3, std::vector< int >( 2 ) );
I'd do this like this:
typedef std::vector< int > SomeLogicalName; // or just IntVector
std::vector< SomeLogicalName > x( 3, SomeLogicalName( 2 ) );
Upvotes: 4
Reputation: 234394
To destroy dynamically allocated arrays you must use delete[]
, not delete
.
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.
#include <vector>
int main ()
{
std::vector<std::vector<int>> x(3, std::vector<int>(2));
}
Upvotes: 10