Hmm, would there be any terrible side effects if delete[] was called on something allocated with new? (as in, calling delete[] on a single entity)
Hmm, would there be any terrible side effects if delete[] was called on something allocated with new? (as in, calling delete[] on a single entity)
What I was told by one of my C++ teachers, way back when, is that when you allocate with new[], the size you allocated is stored somewhere in the allocated block so that when delete[] is called it knows how much to free. If that is indeed the case then whatever value is in that spot is how much will be freed.
So, that would in fact be a terrible side effect... Someone please correct me if I am wrong.
No.Originally posted by Eibro
Hmm, would there be any terrible side effects if delete[] was called on something allocated with new? (as in, calling delete[] on a single entity)
Code:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 0; }
Yes!
I tried compiling this under VC++ 7.1 (about the most standardized compiler out there)
Without the [], I get the proper output:Code:#include <iostream> int i; class C{ public: C(){ std::cout << "Construct." << std::endl; i = 0; } ~C(){ std::cout << "Destruct " << ++i << std::endl; } }; int main(){ C* myC = new C; delete[] myC; }
Construct.
Destruct 1
With the [], a debug build fails an assertation. In a release build the destructor keeps getting called over and over; I terminated the program when it was well into the 50,000s.
Bottom line: Under some compilers, it might work, but under most, it probably won't. And the C++ standard makes no guarantees about anything; it is undefined behavior to use delete[] on something allocated with new, just as it's undefined to use delete on something allocated with new[].
Note that it would be perfectly legal if I used "C* myC = new C[1];". In fact, if I used that form, it would be illegal to call delete instead of delete[].
As an aside, it is even legal to say "new C[0]". It doesn't do anything, but in many cases it makes code simpler to just allow zero-length arrays versus having to check for positive lengths.
Last edited by Cat; 07-22-2003 at 11:37 PM.
On some older compilers the delete [] does not even compile which is strange. I think Turbo C++ does use it, but Borland C++ 4.52 for Windows does not - or the other way around, I forget.