Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

07
Dec

Differences between new, malloc; delete, free

Related Blog Items

It is perfectly legal to use

  • malloc() and delete in the same program, or to use new and free() in the same program. But it is illegal, immoral, and despicable to call free() with a pointer allocated via new, or to call delete on a pointer allocated via malloc().
  • Constructors/destructors: are aware of constructors and destructors, that means new OpenClass() calls OpenClass’s constructor. Similarly, delete p calls *p’s destructor, where as malloc(sizeof(OpenClass)), doesn’t invoke any constructor.
  • Type safety: malloc() returns a void* which isn’t type safe. new OpenClass() returns a pointer of the right type (a OpenClass*).
  • Overridability: new is an operator that can be overridden by a class, while malloc() is not overridable on a per-class basis.
  • using realloc() on pointers allocated via new

    When realloc() has to copy the allocation, it uses a bitwise copy operation, which will tear many C++ objects to shreds. C++ objects should be allowed to copy themselves. They use their own copy constructor or assignment operator.

    Besides all that, the heap that new uses may not be the same as the heap that malloc() and realloc() use!

 

Popularity: 15%

You need to log on to convert this article into PDF


Related Blog Items

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image