I am studying pointers atm. and I got confused with delete[] operator. Here is an example:
int* a = new int[12];
for (int i=0; i<12; i++)
a[i]=123;
delete[] a;
for (int i=0; i<12; i++)
cout <<a[i]<<" ";
If I got it correctly, delete[]
operator should destory all objects in an array.
But my output is this:
10621288 10617028 123 123 123 123 123 123 123 123 123 123
Only first two elements are destroyed. Have I made something wrong?
What you have done wrong is trying to access the contents of a
after it has been deleted. This invokes undefined behavior (UB), which means "anything goes". You must never do that, it is a crash-worthy bug in the code.
The results you see are simply one particular specialization of "anything". Running this program on another system, or using a different compiler, or using the same compiler with different settings, is likely to end up doing something else.