My code:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int * p;
p = new int[5];
p[0] = 34;
p[1] = 35;
p[2] = 36;
p[3] = 44;
p[4] = 32;
cout << "Before deletion: " << endl;
for (int i = 0; i < 5; i++)
{
cout << p[i] << endl;
}
delete[] p;
cout << "After deletion: " << endl;
for (int i = 0; i < 5; i++)
{
cout << p[i] << endl;
}
}
If delete[]
is supposed to delete all the memory blocks created by the new
then why does only the first two elements get deleted here?
This is the output:
Before deletion:
34
35
36
44
32
After deletion:
0
0
36
44
32
One possible reason I could think of is that it removes the first two which some how makes the memory management think that the whole block is free to be reallocated again when needed. Though this is a complete guess on my part and I don't know the real reason.