Click here to Skip to main content
Click here to Skip to main content

To new is C++; To malloc is C; To mix them is sin

, 29 Mar 2004
Rate this:
Please Sign up or sign in to vote.
Article explains the differences between malloc/free and new/delete in a C++ context

Introduction

One of the most common questions that get asked during interviews for C++ programmers is to explain the differences between using malloc and using new. It's also a fairly common question in some of newsgroups and C++ forums. This article will try and explain as simply as possible how malloc and new are two entities that are essentially non-interchangeable, and there is nothing is this article that you wouldn't find in most decent C++ programming books; but the article tries to put all the information together in a single place using simple code snippets and is targeted at newbies who might be unfamiliar as to the differences.

Constructors and Destructors

When you new an object, space for the object is not only allocated but the object's constructor is called. And similarly when you delete an object, the object's destructor is called before the memory is released. If you use malloc and free, the destructor and constructor do not get called respectively and obviously, this simply won't do in C++ except in certain very rare situations where you have classes without any specific destructor/constructors.

It's very easy to test this out by using the following test class.

class  Test
{
public:
    Test()
    {
        cout  <<  "Test  :  ctor\r\n";
    }
    ~Test()
    {
        cout  <<  "Test  :  dtor\r\n";
    }
    void Hello()
    {
        cout  <<  "Test  :  Hello  World\r\n";
    }
};

Create, use and delete the object using new/delete as well as using malloc/free :-

int  _tmain(int  argc,  _TCHAR*  argv[])
{
  cout  <<  "1\r\n";
  Test*  t1  =  new  Test();
  t1->Hello();
  delete  t1;

  cout  <<  "2\r\n";
  Test*  t2  =  (Test*)  malloc(sizeof  Test);
  t2->Hello();
  free(t2);

  return  0;
}

You'll see the following output:-

1
Test : ctor
Test : Hello World
Test : dtor
2
Test : Hello World

As obvious from the output, malloc/free did not result in either the destructor or the constructor being called.

Choosing constructor overloads

For non-array allocations, you can actually specify the specific overload of the constructor that you wish to use as in :- T t = new T(x, y, z); For array allocations using new, the default constructor will get used. If you attempt an array allocation on an object that does not have a default constructor, you get a compiler error :-

class Test2
{
public:
  Test2(int y)
  {    
  }    
};

//...

Test2* t2array = new Test2[10];

For example, if you attempt to compile the above snippet, you'll get an error C2512: 'Test2' : no appropriate default constructor available with the VC++ 7.1 compiler.

Type-casting forced by malloc

Because malloc returns a void* the caller has to do a type-cast to get it to compile.

Test* t1 = new Test();

is so much easier to code and is a lot more readable than

Test* t2 = (Test*) malloc(sizeof Test);

Native types

For native types new/delete and malloc/free work the same way except for the need to type-cast in the case of malloc/free. So it's just a matter of user preference.

//declaring native type

int* i1 = new int;
delete i1;

int* i2 = (int*) malloc(sizeof(int));
free(i2);

//declaring native type array

char** c1 = new char*[10];
delete[] c1;

char** c2 = (char**) malloc(sizeof(char)*10);
free(c2);

Safety tip

Always delete what you new, and free what you malloc, never mix new with free or malloc with delete.

The reason for this is that if you do that, then the behavior is technically undefined because there is no guarantee that new would internally use malloc, or that delete would internally use free.

Tip for scalar and vector new/delete

Thanks to Mike Dunn for referring me to Raymond Chen's blog on this issue. The basic point is that you should not mix scalar new with vector delete and vice versa.

Test* t = new Test[3]; 
delete t; // <-- This is very bad

The above code will result in a memory leak as only the first Test object is deleted.

Test* t = new Test; 
delete[] t; // <-- This is even worse

Similarly, the above code snippet is just as bad and probably worse by a good deal. The vector delete will try to delete more objects depending on the random value it gets from its object-count location and will obviously result in heap corruption.

No realloc alternative for new/delete

The new/delete couple not have a realloc alternative that is available when you use the malloc/free pair. realloc is pretty handy if you want to resize the length of an array or a memory block dynamically, specially since the contents of the array/block remain same up to the shorter of the old and new sizes. To see this in action, see the following code snippet :-

char* p = (char*)malloc(sizeof(char)*12);
strcpy(p,"hello world");
cout << p << "\r\n";
p = (char*)realloc(p, sizeof(char)*24);
strcat(p," from Nish");
cout << p << "\r\n";
free(p);

The output you get will be :-

hello world
hello world from Nish

As you can see from the output, the original contents were retained. Thanks to Minox for reminding me of the realloc issue.

Conclusion

Please feel free to send in further information on new/delete/malloc/free so that I can enhance the article.

Acknowledgements

History

  • Mar 29, 2004 - First published
  • Mar 30, 2004 - Updated
    • Added stuff on scalar/vector mixing with new/delete
    • Added stuff on realloc

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Nish Sivakumar

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Comments and Discussions

 
GeneralMy vote of 5 PinprofessionalManikandan1028-Jun-14 4:13 
GeneralMy vote of 1 PinmemberMy2Cents16-May-09 1:08 
Questionnew and default constructor? Pinmemberseskapill18-Dec-08 1:33 
AnswerRe: new and default constructor? PinmemberArne Mertz17-Jun-13 22:04 
Questionwhat!? Pinmemberpdxmusl9-Oct-08 18:06 
This is one of the topics that bugs me the most when discussing C++ with newbies. This is a serious limitation of c++. Simply stated... There is absolutely NO difference between malloc and the new operator. In fact, "new" CALLS malloc. New is just a "visual basic" or "php" style keyword. Nothing more. Yes, utilizing new does call the constructor of a class, and malloc does not call the constructor. That is a difference, if you look at it from a high level. But we are talking about the guts here. C++ really should be supplying a better way to call a constructor without the use of a new operator (not really taking into account things like copy constructors here...but thank you for that vote). Actually, I have on many occasions used realloc on an array that I have allocated with new. The new operator is a convenient tool, and to claim that mixing the two is a bad practice?? That comes from someone who doesn't really understand the art of programming. Not everything in code SHOULD or CAN be defined as or part of a class. If the entirety of your program is all classes, not always, but very likely you have done something wrong. Or at least you are likely missing a better approach. There is just no good reason why you SHOULDN'T be mixing c-style and C++ coding techniques. Whether you are a hard core c programmer, or a hard core C++ programmer. In fact, the ONLY reason I can think of to maintain an entire set of code at the class (c++) OR c level is because you want it to look pretty. The entire reason why C++ supports c-style coding is BECAUSE they are intended to work together. It's not because of the common misconception that C++ is a odd "c 2.0" version. C++ is an entirely different language which SUPPORTS c-style coding, not includes.
AnswerRe: what!? PinmemberChrisMcB6-Nov-09 9:15 
Questiondoubt Pinmembervikasetrx9-Jul-07 0:22 
Generalone more prominent difference Pinmemberpasisathe15-May-07 16:59 
GeneralRe: one more prominent difference PinmemberLoLSlothboy16-Oct-07 2:10 
Generalone more difference Pinmemberpasisathe15-May-07 16:55 
QuestionBetter way? PinmemberAmro Fawzy24-Apr-07 0:09 
AnswerRe: Better way? PinmvpNishant Sivakumar24-Apr-07 3:55 
GeneralRe: Better way? PinmemberAmro Fawzy24-Apr-07 4:28 
GeneralMSMQ PinmemberKirubanandam7-Jun-05 18:37 
GeneralNew/Delete Scope PinsussCypress star14-Jan-05 6:32 
GeneralRe: New/Delete Scope Pinmemberjan larsen25-May-05 1:04 
GeneralRe: New/Delete Scope Pinmemberavsrivastava17-Aug-06 9:48 
GeneralStrdup - Duplicating/Freeing strings using New PinmemberJS7827-Apr-04 22:14 
GeneralRe: Strdup - Duplicating/Freeing strings using New PinsussAnonymous27-Apr-04 22:36 
GeneralNon-default Heaps PinmemberMike Dimmick8-Apr-04 9:26 
QuestionIs a mistake? Pinmemberwycolor6-Apr-04 15:11 
AnswerRe: Is a mistake? Pinmemberbadecas24-Jun-09 3:19 
Generaltell the right way of coding PinmemberKarthik Murugan30-Mar-04 17:26 
GeneralRe: tell the right way of coding PinstaffNishant S30-Mar-04 17:42 
GeneralRe: tell the right way of coding PinmemberChristian Graus30-Mar-04 18:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 30 Mar 2004
Article Copyright 2004 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid