Why is this code throwing an exception when using dynamic memory allocation?

0

The below program creates a new array of structs of [n+5] elements, every time the quantity reaches 5, 10, 15, ... and copies the old elements to a new array.

This is the error thrown:

Exception thrown at 0x7AE740DF (vcruntime140d.dll) in ConsoleApplication4.exe: 0xC0000005: Access violation writing location 0x6CBFEBB8.

The error is thrown on line 69, where it says items += 1;

#include <iostream>
#include <iomanip>

using namespace std;

struct item{
    string name;
    int eff;
};

item* ptr = nullptr;
item* temp = nullptr;
int itemsA = 0;
int arrSize = 5;
int lastElement = 0;


void func(int&, item *& ,int&, int& , item*&);

int main()
{
    ptr = new item[arrSize];

    func(arrSize, ptr,itemsA,lastElement, temp);


}
void func(int& arrSize, item *& ptr, int &items, int&lastElement, item *& temp)
{
    bool event = false;
    int a = 1;
    while (a == 1)
    {
        cout << "Your array size is: " << arrSize << endl;
        if (items > arrSize)
        {
            temp = new item[arrSize];

            for (int x = 0; x < arrSize; x++)
            {
                temp[x].eff = ptr[x].eff;
                temp[x].name = ptr[x].name;
            }
            arrSize += 5;
            delete[] ptr;
            ptr = nullptr;
            ptr = new item[arrSize];

            for (int x = 0; x < arrSize; x++)
            {
                ptr[x].name = temp[x].name;
                ptr[x].eff = temp[x].eff;
            }
            delete[] temp;
            temp = nullptr;

        }
        int any;
        string any2;
        cout << "ENter name for position number: " << lastElement + 1 << "\n";
        cin >> any2;
        cout << "ENter int for hp effect for position number: " << lastElement + 1 << "\n";
        cin >> any;
        ptr[lastElement].eff = any;
        ptr[lastElement].name = any2;
        items +=1;                                //////////the error is thrown here
        cout << "You now have " << items << " items.\n";


        cout << "Items in your bag: \n";
        for (int x = 0; x < items; x++)
        {
            cout << ptr[x].name << " which gives you extra " << ptr[x].eff << " health when used.\n";
        }
        lastElement += 1;

    }
}
c++
pointers
exception
memory
dynamic
asked on Stack Overflow Mar 19, 2020 by Michael Michael • edited Mar 19, 2020 by Remy Lebeau

1 Answer

1

You're accessing the array out of bounds. When items == arrSize, you try to write to ptr[lastElement], which, since lastElement and items will have the same value, will write to ptr[arrSize] which is past the end of the allocated space.

There are also numerous problems in your array expansion code, and you're passing parameters that you don't need to.

answered on Stack Overflow Mar 19, 2020 by 1201ProgramAlarm

User contributions licensed under CC BY-SA 3.0