delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/09/17/20:30:32

From: Jack Klein <jackklein AT spamcop DOT net>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: void* conversions & delete
Message-ID: <DmDFOcQB6HcHcteeI9qbj30QmLqv@4ax.com>
References: <8q3f52$1bc$1 AT info DOT cyf-kr DOT edu DOT pl>
X-Newsreader: Forte Agent 1.6/32.525
MIME-Version: 1.0
Lines: 37
Date: Mon, 18 Sep 2000 00:22:15 GMT
NNTP-Posting-Host: 12.75.161.153
X-Complaints-To: abuse AT worldnet DOT att DOT net
X-Trace: bgtnsc05-news.ops.worldnet.att.net 969236535 12.75.161.153 (Mon, 18 Sep 2000 00:22:15 GMT)
NNTP-Posting-Date: Mon, 18 Sep 2000 00:22:15 GMT
Organization: AT&T Worldnet
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

On Mon, 18 Sep 2000 00:00:14 +0200, "Rafał Maj" <r_maj AT poczta DOT onet DOT pl>
wrote in comp.os.msdos.djgpp:

> Hi,
> is this code correct :
> 
> int *pos = new int[2];
> void* var = (void*)pos;
> delete []((int*)var);
> 
> I'm not sure, will everything be o.k. when I'll temporarly store adress of
> int[] array    in    void*
> If this example has bug, how to fix it ?
> 
> Thanks,
> Rafal

This is perfectly OK as long as you use the proper type of pointer
when you use delete or delete[] on it.

Both C and C++ guarantee that:

1.  You can store a pointer to any object type in a pointer to void
(requires a cast in C++, not in C).

2.  Assign or cast that pointer value back to a pointer to the
original type.

3.  The final result will point to the same object.

So assigning pos to a pointer to void, and casting that pointer to
void back to pointer to int produces a pointer to int that still
points to the first of the two ints allocated to pos.

Jack Klein
-- 
Home: http://jackklein.home.att.net

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019