Hello all, I started learning C++ a few days ago, using visual C++. I'm learning from an old textbook. I'm having some errors come up due to heap corruption.

The author of this book defined a class matrix and vector (I won't repost the whole thing as it's quite long, I'll post only the important parts)

The important constructors are for a vector:

```
class vector {
friend class matrix;
private:
int size;
double *vec;
public:
vector(int n) {
size = n; //length of vector
vec = new double [size];
if (!vec)
error("allocation failure in vector::vector(int)!");
for (int i = 0 ; i < size; ++i) vec[i]=0;
}
vector& operator=(const vector&); //assignment operator
..................
};
vector& vector::operator=(const vector&v){
if (size != v.size)
error("diff size in vector& vector::op=(const vector&)!");
for (int i = 0 ; i < size; ++i) vec[i] = v.vec[i];
return *this;
}
```

and two constructors for matrices:

```
class matrix {
private:
int numrows; //number of rows
int numcols; //number of columns
vector **mat;
public:
matrix(int, int);
matrix(int);
...............
};
matrix::matrix(int nrows, int ncols)
{ numrows = nrows; numcols = ncols;
mat = new vector* [numrows]; //create an array of vectors
if (!mat) error("row alloc failure in matrix::matrix(int, int)");
for( int i = 0 ; i < numrows; ++i )
{ mat[i] = new vector(numcols); //initialize vector of length ncols
if (!mat[i]) error("col alloc failure in matrix::matrix(int, int)");
}
}
matrix::matrix(int n)
{ numrows = numcols = n;
mat = new vector* [numrows];
if (!mat) error("row alloc failure in matrix::matrix(int, int)");
for( int i = 0 ; i < numrows; ++i )
{ mat[i] = new vector(numcols);
if (!mat[i]) error("col alloc failure in matrix::matrix(int, int)");
}
}
```

so a matrix points to an array of vectors. The values of a matrix should be initialized to 0, as seen from the vector constructor.

If I write the following code:

```
void main() {
int n = 3;
matrix m(n,n);
matrix p(n);
output("\nmatrix m: \n",m);
output("\nmatrix p: \n",p);
}
```

I get an output of two 3x3 matrices where all components = 0, as expected. "Output" function just outputs it in a readable way.

However, some numerical methods use rectangular matrices, when I write code like this:

```
void main() {
int n = 3;
matrix m(n,n+1);
output("\nmatrix m: \n",m);
}
```

or:

```
void main() {
int n = 3;
matrix m(n+1,n);
output("\nmatrix m: \n",m);
}
```

In the first instance the matrix is printed, but an error comes up saying that "Heap corruption detected, after normal block x at y crt detected that the application wrote to memory after end of heap buffer" in the second case no output is printed and the program crashes. So square matrices are fine but rectangular ones do not work. I've looked back through the code and I suspect it might be something to do with it writing to an array after it is full, but I can't seem to find the solution. I'd appreciate any help.