Search code examples
c++dynamiccorruptionheap-corruption

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)


Solution

  • 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.