Jeff Schwab
12/18/2008 4:49:00 PM
James Kanze wrote:
> On Dec 17, 6:23 pm, Jeff Schwab <j...@schwabcenter.com> wrote:
>> Andrey Tarasevich wrote:
>>> If the memory is allocated with 'malloc/calloc', then you
>>> simply cannot deallocate if with 'delete', period. There's
>>> not much sense in discussing the "dangers" of trying to do
>>> so.
>
>> I'm not aware of any guarantee that deleting malloc'd memory
>> will not free the memory. In fact, this is exactly what
>> happens on some platforms. "Simply cannot" is overstating the
>> case.
>
> It's undefined behavior. In theory, an implementation could
> define it, but they'd have to do so in a way that would work
> with any user supplied global operator new/operator delete as
> well. In practice, it's quite likely to cause problems as soon
> as you replace the global new/delete operators (say with
> debugging versions).
With you so far...
> So "simply cannot" applies, just as it applies for using an
> uninitialized variable, dereferencing a null pointer, using an
> object after it has been freed, etc.
None of those things "simply cannot" be done. They're just likely to
cause problems (since they invoke UB). Saying you "simply cannot
deallocate" malloc'd memory with delete implies a guarantee that does
not exist. "You can't do this" is a very different statement from "you
don't do this."
A certain popular operating system used to warn you, when you deleted a
file, that the file would not be recoverable. A lot of individuals and
businesses took that as a guarantee, and were therefore justifiably
surprised when their "deleted" files were recovered by others, often to
devastating effect. Deleting malloc'd memory is certainly not
guaranteed to free the memory, but neither is that behavior prohibited
by the standard. The only blanket statement that can be made is that
it's UB.