0

I'm making a Dynamic Array with templates and classes.

This is the code I'm having issues with:

template<typename GType>
class GArray
{
   GType* array_type = nullptr;
   int size = 0;

public:
GArray(GType Size)
{
    size = Size;
    array_type = new GType[size];

    for (int i = 0; i < size; i++)
        array_type[i] = NULL;
}

void Push(GType Item)
{
    size++;

    GType* temp = new GType[size];

    for (int i = 0; i < size-1; i++)
        temp[i] = array_type[i];

    temp[size] = Item;

    delete[] array_type;
    array_type = temp;
    temp = nullptr;
}

GType& operator[] (int Index)
{
    if (Index >= 0 && Index < size)
        return array_type[Index];
}
};

int main()
{
GArray<int> arr(2);
arr[0] = 10;
arr[1] = 20;
arr.Push(30);


// print array
for (int i = 0; i < arr.Size(); i++)
    cout << arr[i] << endl;

return 0;
}

In the main(), when I print the whole array values, the last one (which should be 30) is an undefined value (like -842150451).

With several tests, I can say that INSIDE the Push() function, the array_type pointer changes. When I come back to the main(), it's like array_type didn't change, it's the same as before.

8
  • Your operator [] does not always return a value! Should not compile Commented Jan 4, 2016 at 11:53
  • 1
    Using case to determine the variable is not a good idea - typos hard to sport (line size = Size;) Commented Jan 4, 2016 at 11:54
  • Should learn about const and reference i.e line ` void Push(GType Item)` should be ` void Push(const GType& Item)` Commented Jan 4, 2016 at 11:55
  • 1
    Yes, the standard defines it as UB: "Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function." — In clang and gcc -Werror=return-type can be used to emit an error. Commented Jan 4, 2016 at 12:15
  • 1
    @Michele - You set the warning level for the compiler. You have to google it as I have not used VS for a while Commented Jan 4, 2016 at 12:16

1 Answer 1

6

The reason for the bug is that

temp[size] = Item

Is wrong. It should be replaced by

temp[size-1] = Item
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.