delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/05/29/00:33:37

Newsgroups: rec.games.design,alt.msdos.programmer,comp.os.msdos.djgpp,rec.games.programmer
From: milod AT netcom DOT com (John DiCamillo)
Subject: Re: C or C++
Message-ID: <milodEAx4r1.2rx@netcom.com>
Organization: Netcom On-Line Services
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>
Date: Thu, 29 May 1997 01:13:49 GMT
Lines: 37
Sender: milod AT netcom16 DOT netcom DOT com
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Nathan Gray <gray AT ll DOT mit DOT edu> writes:

>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.

Sure.  The C standard function "malloc()" attempts to allocate a block
of memory from dynamic storage and returns the address of the newly
allocated block (or 0 if the allocation fails) as a void*.  And that's
all it does.

The C++ operator new also allocates a block of memory for a dynamic
object, but with the following advantages over malloc:

  operator new knows how big the object is (so you can't
  mess up a call to sizeof)

  operator new always calls the default constructor of
  the object's class, and all of its base classes

  operator new returns a pointer of the proper type, so
  you don't need to cast

  operator new can be overloaded on a class by class basis
  to provide special features such as automatic garbage
  collection, memory allocation diagnostics, and preformatted
  memory pools

Rule of thumb: If you are writing C++ code, always use new instead
of malloc().

-- 
    ciao,
    milo
================================================================
    John DiCamillo                         Fiery the Angels Fell 
    milod AT netcom DOT com       Deep thunder rode around their shores

- Raw text -


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