From: Jason Shankel Newsgroups: rec.games.design,alt.msdos.programmer,comp.os.msdos.djgpp,rec.games.programmer Subject: Re: C or C++ Date: Wed, 28 May 1997 15:33:12 -0700 Organization: CCnet Communications (510-988-7140 guest) Lines: 34 Message-ID: <338CB2A8.65EA@nospam.pobox.com> References: <5lrt2d$qun AT bambam DOT soi DOT city DOT ac DOT uk> <5mftso$2nc AT butch DOT lmms DOT lmco DOT com> <338C31B9 DOT 3146 AT ll DOT mit DOT edu> <5mhr54$6ph AT chaos DOT dac DOT neu DOT edu> Reply-To: shankel AT nospam DOT pobox DOT com NNTP-Posting-Host: 207.21.9.48 Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk ferruccio barletta wrote: > > Nathan Gray (gray AT ll DOT mit DOT edu) wrote: > : Since we're on the subject of C and C++, does anyone have a good > : explanation for the differences between malloc() and new? As a native > : C++ programmer, my first instinct is to use new, but I see malloc() so > : often I'm starting to wonder if I'm missing something. > > The only difference that I know of between new/delete and malloc/free is > that new/delete will call the appropriate constructors & destructors > whereas malloc/free simply allocates & frees memory. > > FGB There are a few other differences. malloc() returns 0 on failure, the global new throws an exception. The result is that you do not have to check the return value of new. 'new' is a class operator and can be overloaded on a per-class basis. This means that some classes might not even allocate memory when new is called for them (i.e. an IO mapping class might insert itself at a known address, rather than allocate storage from the heap), others can use custom memory management technqies. malloc(), on the other hand, is defined to allocate memory from the free store. 'new' allows you to install a handler callback to handle out-of-memory conditions, giving you an opportunity to free up unused memory during a 'new' call if new can't allocate sufficient memory. The following construction: MyClass *pMyClass = (MyClass *)malloc(sizeof(MyClass)); is undefined for classes with virtual functions. Jason Shankel, Maxis, Inc.