0

I am having following code

namespace VenkataLibrary {

template <class T>
class DoubleArray {
private:
    T* m_pArray;

    unsigned int m_uiBase; // base to note is array index starts from 0 or 1.
    unsigned int m_rows;
    unsigned int m_columns;

    class Row {
        unsigned int m_uiRow;
        DoubleArray& m_dblArray;
    public:
        Row(unsigned int rowNo, DoubleArray& dblArray) : m_uiRow(rowNo), m_dblArray(dblArray) { }

        T& operator[](const int column) {
            return m_dblArray.select(m_uiRow, column);
        }
    };

public: 

    DoubleArray(unsigned int rows, unsigned int columns) : m_rows(rows), m_columns(columns) {
        m_pArray = new T(m_rows * m_columns);
         memset((void*)m_pArray, 0x00, sizeof(T) * (m_rows-1) * (m_columns-1)); **// I am initializing memory to zero**
    }

    Row operator[] (unsigned int uiRow) {
        return Row(uiRow, *this);
    }

    T& select(unsigned int uiRow, unsigned int uiCol) {
        return m_pArray[uiRow * m_columns + uiCol];
    }
};

};

void main() {

    Array<unsigned int> myIntArray(10, 0);
    DoubleArray<unsigned int> myDblArray(10, 10);

    cout << myDblArray[1][1] << std::endl; **// System crashes here. And I am expecting zero** here.

    myIntArray[0] = 2;

     cout << myIntArray[0] << std::endl;
}

What is the problem ? I think I am not doing initialization proper.

venkysmarty
  • 10,013
  • 19
  • 87
  • 165
  • 1
    you should debug the program to see the states of the objects at the point of the crash – bolov Jan 02 '15 at 09:58
  • I'm afraid `new T(m_rows * m_columns);` allocates ONE `int` variable and initializes it with `m_rows*m_columns` value... Try using square brackets. – CiaPan Jan 02 '15 at 10:00
  • Why not use `std::vector` instead of raw owning pointer ? – Jarod42 Jan 02 '15 at 10:03

2 Answers2

6

This line:

m_pArray = new T(m_rows * m_columns);

allocates one T, with the value of m_rows * m_columns (this syntax is how you can call a constructor with multiple arguments, although you only have one argument here).

You probably meant:

m_pArray = new T[m_rows * m_columns];
user253751
  • 45,733
  • 5
  • 44
  • 76
  • This is in addition to the other points @NPE already mentioned - which, while they are good points that are likely to cause problems in the future, do not lead directly to your crash. – user253751 Jan 02 '15 at 10:05
1

I can see the following problems with your code:

  • DoubleArray violates the Rule of Three.
  • DoubleArray fails to deallocate the allocated memory.
  • The memset call only initializes part of the array (the last argument should be sizeof(T) * m_rows * m_columns).
  • The return type of main should be int (see What should main() return in C and C++?).
  • As pointed out by immibis@, the new call should use square brackets to allocate an array: new T[m_rows * m_columns]. Using parentheses allocates a scalar.
Community
  • 1
  • 1
NPE
  • 438,426
  • 93
  • 887
  • 970