It’s bothering me what delete [] actually does, so I just tried some code and I was shocked with the results
Test #1:
int main()
{
int *d;
while(true)
{
d = new int[10];
delete []d;
}
}
The program doesn’t consume any memory at all, as expected.
Test #2:
int main()
{
int *d;
while(true)
{
d = new int[10];
delete [](d + 5);
}
}
Though in every loop there should be at least 20 bytes (for the five ints it reserves at the beginning of array) reserved which are not deleted this program also doesn’t consume any memory!
Test #3:
int main()
{
int *d;
while(true)
{
d = new int[10];
delete []d;
*d=1;
}
}
This one caused access violation as expected (seems all the memory is deleted after delete []d).
Test #4:
int main()
{
int *d;
while(true)
{
d = new int[10];
delete [](d+5);
*d=1;
}
}
This one was the most amazing, though the while doesn’t consume any memory the program doesn’t produce any access violations either, I’m just wondering where *d is storing it’s data?
(By the way all programs are compiled using no-optimization!)
Now the main question :
What if I allocated an array and I’ve done working with half of it, can’t I by any chance release that half and keep the other half?
You’re not supposed to worry about what
delete[]actually does. It’s for all intents and purposes a black box with certain rules on how to use it properly. The only time you need to worry about what it needs to actually do is if you’re writing a compiler or a C++ runtime (e.g. operating systems, etc.)With respect to those “certain rules on how to use it properly”, Test #2 and #4 invokes undefined behavior:
“Undefined Behavior” means that anything can happen, including the behavior you just described.
These expressions that you have in Tests #2 and #4 are in violation of 5.3.5/2 and will cause undefined behavior (Test #3 will also cause undefined behavior, but for a different reason).
The
delete[]line violates 5.3.5/2 because pointer value you pass todelete[]wasn’t the same value that was given to you fromnew int[].So if the
new int[]command gives you0xA01D2CE9and you pass in0xA01D2CE9 + 5todelete[], you cannot possibly reason about or predict what will happen because you have broken the rules of the language. What will actually happen will be dependent on how the compiler and/or the operating system handlesnew[]anddelete[]. That can range from nothing wrong happening to completely crashing your system, and everywhere in between.In other words, just don’t write things like
delete [](d + 5);.