www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/03/11/11:09:30

X-Authentication-Warning: hlrz18.hlrz.kfa-juelich.de: hw owned process doing -bs
Date: Thu, 11 Mar 1999 10:00:13 +0100 (MET)
From: Holger Wahlen <H DOT Wahlen AT fz-juelich DOT de>
X-Sender: hw AT hlrz18
To: DJGPP mailing list <djgpp AT delorie DOT com>
Subject: Re: Replacing malloc(size) with new and delete - is that possible
Message-ID: <Pine.GSO.3.95.990311095808.9547A-100000@hlrz18>
MIME-Version: 1.0
Reply-To: djgpp AT delorie DOT com

rpolzer AT gmx DOT de asked:

> Can I do the following: (in C++)
> 
> struct PACKET {
> // ... some data
> char P_DATA[0];
             ^^^
> };

Typo, I guess. (By the way, if you want to use C++ anyway,
the string class may be helpful.)

> PACKET *p;
> 
> p = (PACKET *) new char [i + sizeof(PACKET)]; //this should work

If you mean "*" instead of "+", I guess it should, but
actually all you have to write is
	p = new PACKET [i];
to allocate space for i objects of type PACKET (and to call
the default constructor for each of them); new automatically
takes care of the size calculation and returns a pointer of
the correct type.

> But how to delete p?
> 
> delete p; // memory leak?
> delete [] p; // does THAT work?
> delete [] (char *) p //or that?

Number 2. Golden rule: if you allocate with [], use delete[],
if not, just delete:
	foo* pf = new foo;
	// ... stuff using pf ...
	delete pf;
	bar* pb = new bar [42];
	// ... stuff using pb ...
	delete[] pb;

/HW


- Raw text -


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