Click here to Skip to main content
15,886,639 members
Please Sign up or sign in to vote.
1.23/5 (3 votes)
See more:
difference between new and malloc. What is the advantage of using new as compared to malloc()
Posted
Updated 18-Jan-14 5:30am
v2
Comments
Barakat S. 29-Oct-12 10:48am    
Hey anama, have a look at this question: http://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new. The diffuseness have been explained pretty well from many different aspects.

 
Share this answer
 
new will allocate the memory and call the constructor of the object. (delete will call the destructor and free the memomry).
malloc will only allocate the memory. (it will only free the memory).
 
Share this answer
 
v2
new is a better choice that is you can alloc the memory have the type in your program
The malloc() is only alloc the memory or not have the type
You can see from the MSDN
 
Share this answer
 
new and delete are C++ specific features. They didnt exist in C. malloc is the old school C way to do things. Most of the time, you wont need to use it in C++.

* malloc allocates uninitialized memory. The allocated memory has to be released with free.
* calloc is like malloc but initializes the allocated memory with a constant (0). It needs to be freed with free.
* new initializes the allocated memory by calling the constructor (if its an object). Memory allocated with new should be released with delete (which in turn calls the destructor). It does not need you to manually specify the size you need and cast it to the appropriate type. Thus, its more modern and less prone to errors.
 
Share this answer
 
Comments
fjdiewornncalwe 3-Dec-12 10:04am    
Plagiarized. Cite your source if you copy/paste.
There are other differences between malloc and new. Notably, the most used form of new throws an exception on failure. See "new at cplusplus.com"[^].
 
Share this answer
 
Comments
Stefan_Lang 20-Jan-14 5:19am    
Did you notice the date of the question?
CPallini 20-Jan-14 5:57am    
Nope. 'Agent_Spock' update fouled me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900