problem with templated class

Hi, first thing I should say is that my university course hasn't extended beyond pointers, references, and dynamic memory allocation (for C, course hasnt had any C++ exclusive content until next level). I have been trying to teach myself C++ since I enjoy learning about it, and lately have been trying to familiarize myself with templated classes. Below is a small class I have which should function like a single dimensional array.

It all works as expected/intended, until the program tries to exit. It executes perfectly, however, when it attempts to exit, the program crashes. I have tried many different things but obviously nothing has worked. Can anyone share some light on this? Compiler is mingw/g++
Your program shouldn't compile. Something like T row[]; isn't allowed in C++.
Even if it were you need to call new to allocate the appropriate amount of memory for the row.


T *row;
array_1d<T>::array_1d(const int ilength):
rowlength(ilength), row(new T[ilength])
        cout << "array_1d destructor called" << endl;
        delete[] row; // Note: []
Alright, thanks. Just two questions-
1) Why isnt this allowed? What exactly makes it invalid/crash?
2) Why does it function until the end of the program, and then crash?

Edit: Also, what would be a valid method of doing this?
Last edited on
1) It defines an array with zero length / without elements. Accessing such an element is always out of bounds which means reading from/writing to memory that's not yours.

2) out of bounds operation leads to undefined behaviour. It's unknow what memory you're manipulating. So it's possible that it crashes immediately or never.

keep in mind that c++ doesn't provide any automatism for dynamic memory operations. You need to do it yourself or use libraries such as STL
Topic archived. No new replies allowed.