Dynamic array heap corruption

I have the following class:

template <typename T>
class matrix
{
private:
    int _n;
    T* array;
public:
    matrix(): _n(0) 
    {
        array = new T[_n * _n];
    }
    matrix(int n): _n(n)
    {
        if( n < 0 )
            throw "Invalid array size!";
        array = new T[_n * _n];
    }
    ~matrix()
    {
        delete[] array;
    }
    void Set(const int x, const int y,const T val)
    {
        if( ( x<0 || x>_n ) && ( y<0 || y>_n) )
            throw "Invalid index";
        array[x*_n + y] = val;
    }
    T& Get(const int x, const int y)
    {
        if( ( x<0 || x>_n ) && ( y<0 || y>_n) )
            throw "Invalid index";
        return array[x*_n + y];
    }
};

and using it this way:

matrix<int> k(5);
k.Set(5,5,6);
cout<<k.Get(5,5);

The problem is I get a heap corruption error when calling Set. What am I doing wrong? (my guess is it's the way I access they array elements)

Answers


A 5 element array can be accessed at the indexes 0-4. You're passing 5 for x and y, which results in an invalid index when accessing array.


Need Your Help

Web Service Response returns a 500 Internal Server Error

c# asp.net wcf web-services internal-server-error

I have written my own web service which works fine stand alone. I'm calling this web service from another page, and at that time it returns a 500 Internal Server error. I'm going through this proce...

ios sqlite row with ? not read

ios sqlite

I have my sqlite database already built and is copied on application startup. After that I of course run queries (just select statements). So far all but one query works. After some investigatio...