delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/09/10/19:10:02

Date: Mon, 11 Sep 2000 01:08:00 +0200
From: Egon Eckert <egon AT chance DOT cz>
To: djgpp AT delorie DOT com
Subject: Re: strdup() with delete[]
Message-ID: <20000911010800.C23829@chance.cz>
References: <8pgtns$sja$1 AT info DOT cyf-kr DOT edu DOT pl>
Mime-Version: 1.0
User-Agent: Mutt/1.0.1i
In-Reply-To: <8pgtns$sja$1@info.cyf-kr.edu.pl>; from r_maj@poczta.onet.pl on Sun, Sep 10, 2000 at 11:18:07PM +0200
Reply-To: djgpp AT delorie DOT com
Errors-To: nobody AT delorie DOT com
X-Mailing-List: djgpp AT delorie DOT com
X-Unsubscribes-To: listserv AT delorie DOT com

Err, I did quote your text wrong in my previous reply.  So, once again. :)

> All memory allocated like
>   char* s = new char[100];
> should be deleted using :
>   delete s[];
> right ?

I guess the [] form is considered obsolete.  I would use simple delete s. 
The operator's implementation knows how many objects are allocated.

> And what about allocation done with strdup() :
>   char* s = strdup("test");
> should I use then delete s[];  OR  delete s;  ?

I would call free here (see my previous mail).

> =============
> Is this correct :
>     char *s;
>      if (/*...*/) s=strdup(S);  else  { s=new char[2];  s[0]=ch;
>  s[1]=NULL; }
>     delete s[];

It doesn't make big difference in this case (free or delete), I think using
both is safe here.  Delete performs 'destruction' of all the objects, which
means nothing for 'char'.  One recommendation: I would use

s [1] = 0;

instead of 's [1] = NULL;'.  NULL is a hint for "pointer" value, but you
assign 'char' in this case, no pointer.

BTW: I'm not sure whether it's recommended to use NULL at all in 'modern'
C++, shouldn't we use simply '0' everywhere instead of NULL?

-- 
Egon Eckert, Chance, a.s.
E-mail: egon AT chance DOT cz

- Raw text -


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