From: Jack Klein Newsgroups: comp.os.msdos.djgpp Subject: Re: FINALY: delete/delete[] with build-in-types/user-classes Message-ID: References: <8q1tn2$iv6$1 AT info DOT cyf-kr DOT edu DOT pl> X-Newsreader: Forte Agent 1.6/32.525 MIME-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit Lines: 74 Date: Sun, 17 Sep 2000 08:16:04 GMT NNTP-Posting-Host: 12.75.174.41 X-Complaints-To: abuse AT worldnet DOT att DOT net X-Trace: bgtnsc07-news.ops.worldnet.att.net 969178564 12.75.174.41 (Sun, 17 Sep 2000 08:16:04 GMT) NNTP-Posting-Date: Sun, 17 Sep 2000 08:16:04 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 Sun, 17 Sep 2000 10:00:28 +0200, "Rafał Maj" wrote in comp.os.msdos.djgpp: > Hi, > because my last question about delete / delete[] caused big discusion with > meany diffrent opinions, I wan't to check, if finaly I understand it... > (probably not ;) > 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, that is correct. > b) using delete s; is probably wrong, because none destructor will be > called. But all memory 100*sizeof(myclass) will be freed ? Maybe, maybe not. The C++ language standard states that items created with new[] be destroyed by delete[], and those with new by delete. Combining new[] with delete or new with delete[] is undefined behavior, which means anything can happen. Even if this happens to work with one particular, it might not with the next one. > 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 No, delete after new[] is not good. It is illegal code, it is a bug, it is not valid C++. Even if it seems to work. > 3) and what with char* s = malloc(sizeof(char)*100); ? Actually you can't even compile this as C++, although you can as C. In C++ you can't assign a void * to another type of pointer without a cast. And you never, never need to multiply anything by sizeof(char), since sizeof(char) is 1 by definition, and always will be. The safest way to use malloc() is: char *s = (char *)malloc(100 * sizeof *s); In C, don't use the (char *) cast. > a) free - typical Yes, or realloc() with a size of 0. > b) can I use delete ? No. > c) can I use delete [] ? No. > 4) because strdup() uses malloc, char *s=strdup(S); should be "deleted" > same way as in question 3 > > Many Thanks, > Rafal There are three pairs of memory management functions, and you should never, NEVER, mix them: new & delete new[] & delete[] malloc() or calloc() & free() You can use all of these different methods in the same program for different allocations, but for any given memory block you must free it with the corresponding type you used to allocate it. Jack Klein -- Home: http://jackklein.home.att.net