www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/09/18/16:19:56

Date: Mon, 18 Sep 2000 16:18:22 -0400
Message-Id: <200009182018.QAA21990@envy.delorie.com>
From: DJ Delorie <dj AT delorie DOT com>
To: djgpp AT delorie DOT com
In-reply-to: <8q1tn2$iv6$1@info.cyf-kr.edu.pl> (r_maj@poczta.onet.pl)
Subject: Re: FINALY: delete/delete[] with build-in-types/user-classes
References: <8q1tn2$iv6$1 AT info DOT cyf-kr DOT edu DOT pl>
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

> 1) "s" is a pointer to array, maked like:  myclass* s = new myclass[100];
>    a)  delete []s    will not only free memory, but alsow call destructor
>        for each of 100 objects "myclass"

Yes.

>    b) using delete s;  is probably wrong, because none destructor will be
>       called. But all memory 100*sizeof(myclass) will be freed ?

Yes, but new[] *also* allocates some bookkeeping memory (to keep track
of how many objects need destructors called).  If you don't call
delete[] you'll leak that overhead.  Note: some variants of new/delete
work without this overhead/leak, but don't count on it.

Plus, your destructors might free up memory if the constructors
allocated some.

> 2) with   char *s = new char[100]  I can use :
>   a) delete []s;  but it isn't necessarly, when char doesn't have any
>      destructor
>   b) delete s;  is good

Yes to both, I think.

> 3) and what with   char* s = malloc(sizeof(char)*100); ?
>    a) free - typical

Yes.

>    b) can I use delete ?
>    c) can I use delete [] ?

You shouldn't.  I've seen at least one implementation where new/delete
offset pointers a bit, so that it was *impossible* to mix malloc/free
with new/delete.

> 4) because strdup() uses malloc,   char *s=strdup(S); should be "deleted"
>    same way as in question 3

Yes.

- Raw text -


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