In addition to the fix to your error (see solution 1), there are several errors in the code, some of them severe:
1. on several occasions you allocate your internal array calling
new int[]
rather than
new T[]
2. your method
grow_array()
has some severe issues:
T* p_temp = new T[array_size + 1];p_temp = p_array;array_size++;delete p_array;p_array = p_temp;
- error 1: you just lost your only reference to the newly allocated array - memory leak! Solution: just remove that line!
- error 2: you must use delete[] p_array, else you get a runtime error. There's also the secondary issue that you're losing all the values currently stored in p_array. Didn't you want to copy them to the new array?
- error 3: since p_temp is pointing to the same address p_array is pointing to, this line does nothing at all. However, it does mean that p_array is (still) pointing to invalidated memory, and the next attempt to use it will result in a fatal error that crashes the program! Solution: will be fixed after fixing error 1.
- error 4: the return statement is missing (but then, you don't appear to be using a return value, so you might just as well change the return type to
void
)
3. your method
push_front()
calls
grow_array
, but also redundandly does the required allocation itself.
4. The methods
push_front
and
push_back
query values of
p_array
without checking if it is even defined: if
p_array
is
0
, then this may result in a crash.
5. the method
set
uses
grow_array
in case the index is out of range, but that won't be sufficient if the index is out of range by more than 1. Consequently, the value may be stored at an unexpected location!
And one minor issue:
Your default constructor allocates an array of default length and then initializes all array elements with
NULL
. You should be using
0
here - or better:
p_array[i] = T(0);