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

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



On Tue, Aug 05, 2003 at 03:40:42AM +0200, Sebastian Kapfer wrote:
> On Mon, 04 Aug 2003 05:00:12 +0200, MJM wrote:
> > // change the way it is accessed to prove a point int * p_b = (int *)
> > p_a;
> > // p_a and p_b point to the same block of dyn. allocated memory;
> 
> Do they? Watch out for inheritance, user-defined casting operators and
> other funny stuff. C++ adds a few new meanings to the () casting syntax.
> In general, your assumption is _wrong_.
> 
> > // return the memory to free storage using the second pointer delete
> > p_b;
> > 
> > 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.

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?

Or would it have been better for C++ to have been named D to stop people
wanting to think like this?

-- 
Pigeon

Be kind to pigeons
Get my GPG key here: http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x21C61F7F

Attachment: pgpkO66mWms92.pgp
Description: PGP signature


Reply to: