Class Example
{
// ...
};
int main()
{
Example** pointer = new Example*[9];
for(int i = 0; i < 10; i++)
{
pointer[i] = new Example();
}
for(int i = 0; i < 10; i++)
{
delete pointer[i];
}
delete[] pointer; // <--- This is problem
pointer = nullptr;
}
I'm trying to hold object's adresses in arrays. When I'm trying to delete them, for loop working great but delete[] pointer
causes "wrote to memory end of heap buffer" error. What am I doing wrong? Should'nt I delete that too?
Your array is too small:
Example** pointer = new Example*[9];
You are allocating for 9 elements, meaning their indices are 0,1,2,...,8.
In the loops here:
pointer[i] = new Example();
and here:
delete pointer[i];
you are accessing pointer[9]
because your loop condition is i < 10
. This is out-of-bounds and accessing the value causes undefined behavior.
Instead create an array with 10 elements:
Example** pointer = new Example*[10];