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;
}
}
forloop infunc()accesses elements oftemppast the end. You subsequent code does not check thatlastElementis a valid index forptr, but uses it as an index. Accessing an invalid index of an array (dynamically allocated or not) does not magically resize that array - it simply causes undefined behaviour.a_function_that_first_does_this_and_then_this_but_only_if_thatit's a sure sign that you should split it. Yourmain(proxied via a call to avoid func(int&, item *& ,int&, int& , item*&);) looks like it has some of that.