Below is a snippet of my code for a stack data structure that I am trying to implement.
For some reason when I delete currentArray
, newArray
is deleted too, because the code below is giving me a run-time bug where the contents of newArray
and currentArray
are garbage values.
I'm not sure why this is happening.
Would greatly appreciate any insight as to why I am getting this bug, and if my push()
implementation below is on point from a fundamental perspective.
// Destructor
~Stack()
{
if ((size > 0) && (currentArray) != NULL && (newArray != NULL))
{
delete[] currentArray;
delete[] newArray;
}
}
inline void push(T value)
{
if (isEmpty())
{
// Stack size is increased by 1
size++;
currentArray = new T[size];
currentArray[size - 1] = value;
}
else
{
// Stack size is increased by 1
size++;
// Create the new array
newArray = new T[size];
// Copy the contents of the old array into the new array
copy(currentArray, currentArray + size, newArray);
// Push the new value on to the new array
newArray[size - 1] = value;
// Copy the new array into the current
currentArray = new T[size];
currentArray = newArray;
}
}