[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [OT] C++ question re. dyn. mem.

* Pigeon (jah.pigeon@ukonline.co.uk) [030805 12:52]:
> On Tue, Aug 05, 2003 at 03:40:42AM +0200, Sebastian Kapfer wrote:
> > On Mon, 04 Aug 2003 05:00:12 +0200, MJM wrote:
> > > I think the free store will be maintained properly because there is a
> > > control block attached to the allocated block of storage that defines
> > > the length of the allocated memory.
> > 
> > No. You have to delete the original pointer (with the original type).
> > Everything else is undefined behaviour, i.e. it could work, it could leak
> > memory (completely or partly), it could crash, or even print "42". It
> > might even work sometimes, and fail mysteriously at other times.
> Interesting. I figured that the actual allocation/deallocation would
> end up being handled by a call to malloc() / free(), and free() only
> cares about having the correct value for the (void *) pointer.

It could be, and probably is.  The point is, the behavior is undefined,
and implementation dependent.  As the question was about C++, and not a
particular version of g++, Sebastian's precise answer is the correct
one.  Even if you never intend to port your code, it's best to write it
within the defined behavior of the language, for portability,
maintainability, and (maybe most importantly) to foster good habits in
case next week you find yourself working on a project in which
portability is important.

> Would it not be the case, though, in the barebones example given, that
> MJM's '_wrong_ assumption' would be correct, and 'it' would work, even
> if in a more general case it might not?

I haven't tested it, nor am I familiar enough with g++ to be qualified
to give a canonical answer, but I would guess that it would work.  (If
he hadn't used a bad cast in the instantiation, anyway.)

good times,
One nation, indivisible, with equality, liberty, and justice for all.

Attachment: signature.asc
Description: Digital signature

Reply to: