Possible Duplicate:
How does delete[] “know” the size of the operand array?
How does the delete in C++ know how many memory locations to delete
I know it’s a rather simple question but I a not sure about the difference (if any) between this lines :
double * a = new double[100];
delete[] a;
delete a;
free ((void*)a);
First off, would all of these calls (used each without the others) work the same way and free sizeof(double)*100 bytes?
Which lead me to the 2nd question, how does the program keep track of the size of the allocated memory? For instance if I send my a pointer to a function, then delete[] this pointer from within my function, would I also free the same amount of memory?
Thanks
The difference, oversimplified, is this:
Is correct. All others are incorrect, and will exhibit Undefined Behavior.
Now, in reality, on all the compilers I use daily,
delete a;will do the right thing every time. But you should still not do it. Undefined Behavior is never correct.The
freecall will also probably do the right thing in the real world, but only because the thing you’re freeing doesn’t have a non-default destructor. If you tried tofreesomething that was a class with a destructor, for example, it definitely wouldn’t work — the destructor would never be called.That’s one of the big differences (not the only difference) between
new/deleteandmalloc/free— the former call the constructors and destructors, while the latter meerly allocate and dealocate space.Incorporating something @Rob said in his now-deleted post:
As to the question of how
delete[]knows how many elements to delete, please see this response to a previous duplicate question.