Re: Why 'delete []' for aray?
- From: "Igor Tandetnik" <itandetnik@xxxxxxxx>
- Date: Mon, 11 Feb 2008 09:10:28 -0500
"Sharon" <SharonG@xxxxxxxxxxxxxxxxx> wrote in message
news:5793D864-88E2-424A-B259-1CC517B95DE1@xxxxxxxxxxxxx
For deleting an array, like
BYTE* barray = new BYTE[100];
We use:
delete [] barray;
and not just:
delete barray;
Does he use of delete instead of delete[] will cause a memory leak?
It will cause undefined behavior, meaning anything could happen
(including the program working as expected).
Why? The memory manager knows the size of memory to free by the value
written in VM
But it doesn't know how many elements are in the array, or that, in
fact, the pointer points to an array. And that's needed to call
destructors for array elements (for arrays of class type).
Moreover, when allocating arrays of classes with non-trivial destructor,
the new[] operator allocates more memory than required and writes the
number of elements at the beginning. The pointer returns doesn't point
to the beginning of the allocated memory, but at some byte past the
counter. In other words, the number of elements is stored at the
negative offset from the pointer returned by new[]. delete[] adjusts the
pointer backward, reads the counter, runs destructors, then deallocates
memory. Non-array delete wouldn't know to do that, would only run
destructor for the first element, and finally would pass a wrong pointer
to free().
It just so happens that on this particular implementation, allocating
arrays of types with trivial destructor (including fundamental types)
doesn't do any of this, so both delete and delete[] work on them. Other
implementations may not be so forgiving. I recommend you just do the
right thing in your program.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925
.
- Prev by Date: Re: type safe issue
- Next by Date: Re: extern "C"
- Previous by thread: Re: type safe issue
- Next by thread: Re: Why 'delete []' for aray?
- Index(es):
Relevant Pages
|