305

What is the difference between new/delete and malloc/free?

Related (duplicate?): In what cases do I use malloc vs new?

Community
  • 1
  • 1
MrDatabase
  • 43,245
  • 41
  • 111
  • 153
  • See also my detailed answer [here](http://stackoverflow.com/questions/14574617/what-is-dynamic-memory-allocation-in-c/27630175#27630175). – Jonathan H Dec 24 '14 at 12:19

15 Answers15

503

new / delete

  • Allocate / release memory
    1. Memory allocated from 'Free Store'.
    2. Returns a fully typed pointer.
    3. new (standard version) never returns a NULL (will throw on failure).
    4. Are called with Type-ID (compiler calculates the size).
    5. Has a version explicitly to handle arrays.
    6. Reallocating (to get more space) not handled intuitively (because of copy constructor).
    7. Whether they call malloc / free is implementation defined.
    8. Can add a new memory allocator to deal with low memory (std::set_new_handler).
    9. operator new / operator delete can be overridden legally.
    10. Constructor / destructor used to initialize / destroy the object.

malloc / free

  • Allocate / release memory
    1. Memory allocated from 'Heap'.
    2. Returns a void*.
    3. Returns NULL on failure.
    4. Must specify the size required in bytes.
    5. Allocating array requires manual calculation of space.
    6. Reallocating larger chunk of memory simple (no copy constructor to worry about).
    7. They will NOT call new / delete.
    8. No way to splice user code into the allocation sequence to help with low memory.
    9. malloc / free can NOT be overridden legally.

Table comparison of the features:

Feature new / delete malloc / free
Memory allocated from 'Free Store' 'Heap'
Returns Fully typed pointer void*
On failure Throws (never returns NULL) Returns NULL
Required size Calculated by compiler Must be specified in bytes
Handling arrays Has an explicit version Requires manual calculations
Reallocating Not handled intuitively Simple (no copy constructor)
Call of reverse Implementation defined No
Low memory cases Can add a new memory allocator Not handled by user code
Overridable Yes No
Use of constructor / destructor Yes No

Technically, memory allocated by new comes from the 'Free Store' while memory allocated by malloc comes from the 'Heap'. Whether these two areas are the same is an implementation detail, which is another reason that malloc and new cannot be mixed.

heap underrun
  • 1,846
  • 1
  • 18
  • 22
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • 15
    Can someone edit to elaborate regarding the "Free Store" as opposed to the heap? A process' heap is a well-known language-independent (?) operating-system-level concept; where does the "Free Store" come from? – einpoklum Feb 21 '16 at 15:26
  • 1
    @einpoklum: They are just names of memory areas. Neither has anything to do with the language concept known as "heap" or the os concept of "processes heap". C++ is deliberately defined to be Platform/OS/Compiler neutral. So using a specific OS concept like "processes heap" would undermine the flexibility of the standard. – Martin York Feb 21 '16 at 17:06
  • 1
    Null check is not required for delete. OTOH, free expects non-null pointer. – winterlight Jun 19 '16 at 11:25
  • 4
    @winterlight: That used to be true but no longer. See: http://linux.die.net/man/3/free `If ptr is NULL, no operation is performed.` – Martin York Jun 19 '16 at 17:12
  • 3
    @LokiAstari It does look like 'heap', 'free store', and 'dynamic memory/storage' are synonyms: In Bjarne Stroustrup's **A Tour of C++**, he says "The `new` operator allocates memory from the *free store* (also known as *dynamic memory* and *heap*). The C++ 14 Standard, section 3.7.4 on **Dynamic Storage** says "Objects can be created dynamically during program execution (1.9), using new-expressions (5.3.4), and destroyed using delete-expressions." – Max Heiber Jan 07 '17 at 15:07
  • 1
    @mheiber: The standard explicitly states these can be separate areas. `n4567` 20.7.13 C-Library paragraph 5 (about malloc): `It also allows malloc() to be implemented with a separate allocation arena,` – Martin York Jan 08 '17 at 19:55
  • @LokiAstari interesting, but I'm not sure "allowed to be in a separate allocation arena" implies that 'free store' is a different concept from 'heap.' But then, I'm not really clear on what 'separate allocation arena' means. It's probably specific to the semantics of `undeclare_unreachable`, which is what that paragraph is about. – Max Heiber Jan 09 '17 at 15:46
  • 2
    @mheiber: It means they can be the same. And several implementations implement new by calling malloc (note the other way around is explicitly not allowed). But several implementations keep those memory areas completely separate. The reason too kept them separate is that this allows C++ memory management code to be optimized in a different way than the C memory management. The point is: They could be the same but you can't assume that they are. – Martin York Jan 09 '17 at 17:43
  • 1
    @mheiber: You have to remember that new/delete are integral parts of the C++ language and allocate and release from the 12.5 "Free Store". While malloc and family are provided as a library from a completely different language that knows nothing about C++. In the C standard malloc/free get memory from the "Heap". Now C++ internally is allowed to use malloc underneath the hood there is no requirement for it to do so. – Martin York Jan 09 '17 at 17:56
  • 1
    @mheiber: Also "A Tour of C++" is designed for beginners so making things trivial to understand is more important than the actual implementation details. Especially when it makes little difference at the application level. All you need to remember is that a pointer allocated with new must be released by delete (not free) and a pointer allocated with malloc must be released by free (not delete). – Martin York Jan 09 '17 at 17:58
  • The difference between "Free Store" and "Heap" promoted by this answer is not supported by the standard, as neither the C nor the C++ standards mention the word "heap" in that context. (C has no mention of it at all, and C++ talks of heaps only in the [data structure](https://en.wikipedia.org/wiki/Heap_(data_structure)) sense.) – user4815162342 Feb 25 '17 at 11:05
  • @user4815162342: The term "Free Store" is defined by the C++ standard. The term 'Heap' (always quoted) is used here merely to distinguish that the two allocation arenas are allowed to be distinct (without having to write a book about the differences). – Martin York Feb 25 '17 at 22:01
  • The answer quotes both heap and free store. Why not simply specify that they are distinct without introducing a specific term for one of them? After all, "heap" is normally used for any dynamic memory arena, including the memory allocated by `new`. (And it is also used by C++ to refer to the data structure, which can only add to the confusion.) – user4815162342 Feb 26 '17 at 01:08
  • @user4815162342: Which you would have found if you had only read the first **two** comments. – Martin York Feb 26 '17 at 02:20
  • By "why not specify" I was referring to the text of the answer. (Admittedly, the word "specify" was easy to misunderstand in the context.) Your comment was about the wording of the standard. – user4815162342 Feb 26 '17 at 07:44
  • 1
    Not sure if it matters to anyone but you can get the 'new' keyword to return a null pointer rather than a 'bad_alloc' by using (notthrow) during the instantiation of the pointer: foo = new (nothrow) int [5]; – Rob Mar 07 '19 at 18:17
86

The most relevant difference is that the new operator allocates memory then calls the constructor, and delete calls the destructor then deallocates the memory.

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
Trap
  • 12,050
  • 15
  • 55
  • 67
  • 24
    Strictly speaking, the new operator just allocates the memory. It is the new expression which calls the new operator, then runs the constructor in the allocated memory. – Don Wakefield Oct 27 '08 at 23:36
  • Another difference is where the memory is allocated. I recently saw somewhere that malloc/free operate on the heap, while new/delete operate in another area of memory whose name eludes me now. (Suffice it to say, though, that other area can probably be thought of as another heap.) – RobH Apr 30 '09 at 19:29
  • RobH - all memory is allocate don the heap. Local variables are on the stack. 'new' and malloc are normally the same function except for the subsequent calling of the ctors. – Martin Beckett Oct 06 '09 at 19:37
  • 2
    @mgb: Yes you are correct that objects are allocated on either the "Application heap" or stack. __But__ @RobH is referring to what the standard calls different parts of the "Application Heap". There is the "Heap" which is where malloc allocates memory from and "Free Store" where new allocates memory from. Though in __some__ implementations these areas do overlap (this is an implementation detail). – Martin York Nov 28 '09 at 02:01
  • 1
    You statement is 100% correct but just doesn't answer the question asked, see the answer below, there is a reason why it more votes than yours. – Murali Jan 20 '10 at 16:58
  • Here's an extended version of my answer so you can understand: "The most relevant difference is that the new operator allocates memory then calls the constructor, and delete calls the destructor then deallocates the memory, [as opposed to malloc/free which do not call ctors/dtors]" I'd say that a single downvote (yours), 30 upvotes and 2 revisions still qualifies as a good answer, which means that most of people understand it. And yes, the reason is that Martin's answer is better than mine (it has 14 revisions) Btw, I also upvoted his. – Trap Jan 21 '10 at 01:23
  • 1
    All I was trying to say was there should be at least some mention of malloc/free for it to qualify as a comparison which your answer lacked. Nevertheless, it is a relevant and accurate statement, so the upvotes, I hope you understand my point. Anyway, if only SO allowed me to take my downvote back, I wholeheartedly would. – Murali Jan 22 '10 at 03:06
  • @wizard. Your down vote got me a gold badge so I am fine. Anyweay I like the succinct answer to be the first one. If people need more information they can scroll down. – Martin York Jan 26 '10 at 19:57
  • @Trap your answer doesn't answer the question, "extended" version is really extended (and that answer the question), however I really like Don Wakefield comment – 4pie0 Sep 01 '13 at 01:21
  • @DonWakefield: The distinction between raw allocation and object creation indeed exists, however your terminology is wrong. Where you said "new operator" you meant "(global or member) function named `operator new()`". Wherever the "new operator" appears, it is a *new-expression* and does call the constructor, there is no meaningful distinction between the two terms you used in your comment. – Ben Voigt Sep 15 '17 at 21:20
31

new calls the ctor of the object, delete call the dtor.

malloc & free just allocate and release raw memory.

James Curran
  • 101,701
  • 37
  • 181
  • 258
17

new/delete is C++, malloc/free comes from good old C.

In C++, new calls an objects constructor and delete calls the destructor.

malloc and free, coming from the dark ages before OO, only allocate and free the memory, without executing any code of the object.

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
Treb
  • 19,903
  • 7
  • 54
  • 87
  • 10
    "Coming from the dark ages before OO" sounds like you're implying that new/delete are *better* than malloc/free when in reality, neither is better or worse, they just have different uses. Note that I'm not the ont that downvoted you, I'm just guessing. – Graeme Perrow Oct 27 '08 at 15:19
13

In C++ new/delete call the Constructor/Destructor accordingly.

malloc/free simply allocate memory from the heap. new/delete allocate memory as well.

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
Encryptic
  • 189
  • 6
13

The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor.

There are other differences:

  • new is type-safe, malloc returns objects of type void*

  • new throws an exception on error, malloc returns NULL and sets errno

  • new is an operator and can be overloaded, malloc is a function and cannot be overloaded

  • new[], which allocates arrays, is more intuitive and type-safe than malloc

  • malloc-derived allocations can be resized via realloc, new-derived allocations cannot be resized

  • malloc can allocate an N-byte chunk of memory, new must be asked to allocate an array of, say, char types

Looking at the differences, a summary is malloc is C-esque, new is C++-esque. Use the one that feels right for your code base.

Although it is legal for new and malloc to be implemented using different memory allocation algorithms, on most systems new is internally implemented using malloc, yielding no system-level difference.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Walter
  • 443
  • 4
  • 11
10

The only similarities are that malloc/new both return a pointer which addresses some memory on the heap, and they both guarantee that once such a block of memory has been returned, it won't be returned again unless you free/delete it first. That is, they both "allocate" memory.

However, new/delete perform arbitrary other work in addition, via constructors, destructors and operator overloading. malloc/free only ever allocate and free memory.

In fact, new is sufficiently customisable that it doesn't necessarily return memory from the heap, or even allocate memory at all. However the default new does.

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
5

There are a few things which new does that malloc doesn’t:

  1. new constructs the object by calling the constructor of that object
  2. new doesn’t require typecasting of allocated memory.
  3. It doesn’t require an amount of memory to be allocated, rather it requires a number of objects to be constructed.

So, if you use malloc, then you need to do above things explicitly, which is not always practical. Additionally, new can be overloaded but malloc can’t be.

In a word, if you use C++, try to use new as much as possible.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
4

also,

the global new and delete can be overridden, malloc/free cannot.

further more new and delete can be overridden per type.

DanJ
  • 3,435
  • 3
  • 33
  • 44
3

new and delete are C++ primitives which declare a new instance of a class or delete it (thus invoking the destructor of the class for the instance).

malloc and free are C functions and they allocate and free memory blocks (in size).

Both use the heap to make the allocation. malloc and free are nonetheless more "low level" as they just reserve a chunk of memory space which will probably be associated with a pointer. No structures are created around that memory (unless you consider a C array to be a structure).

OmarOthman
  • 1,718
  • 2
  • 19
  • 36
Jorge Córdoba
  • 51,063
  • 11
  • 80
  • 130
  • 1
    new in C++ doesn't declare an instance of a class. It (usually) allocates one from the heap, and it doesn't declare anything. You can declare an instance just by declaring it, in which case it will be on the stack, or in globals, depending on the storage duration of the declaration. – Steve Jessop Oct 27 '08 at 15:14
  • Well, it allocates the memory space for the class but you can't "declare" a class in the stack, not in the real sense of storing the class in the stack. The declaration involves just the pointer to the class which is always allocated in the stack the actual memory holding the class is in the heap. – Jorge Córdoba Oct 27 '08 at 15:28
  • Yes you can. According to the question tags this is C++, so objects can go on the stack. And new isn't a declaration, it's an expression. Declaring something and allocating it are separate things. – Steve Jessop Oct 27 '08 at 15:40
3
  • new is an operator, whereas malloc() is a fucntion.
  • new returns exact data type, while malloc() returns void * (pointer of type void).
  • malloc(), memory is not initialized and default value is garbage, whereas in case of new, memory is initialized with default value, like with 'zero (0)' in case on int.
  • delete and free() both can be used for 'NULL' pointers.
Anurag Singh
  • 492
  • 6
  • 16
2

new and delete are operators in c++; which can be overloaded too. malloc and free are function in c;

malloc returns null ptr when fails while new throws exception.

address returned by malloc need to by type casted again as it returns the (void*)malloc(size) New return the typed pointer.

0
  • To use the malloc(), we need to include <stdlib.h> or <alloc.h> in the program which is not required for new.
  • new and delete can be overloaded but malloc can not.
  • Using the placement new, we can pass the address where we want to allocate memory but this is not possible in case of malloc.
ron davis
  • 65
  • 4
0

This code for use of delete keyword or free function. But when create a pointer object using 'malloc' or 'new' and deallocate object memory using delete even that object pointer can be call function in the class. After that use free instead of delete then also it works after free statement , but when use both then only pointer object can't call to function in class.. the code is as follows :

#include<iostream>


using namespace std;

class ABC{
public: ABC(){
    cout<<"Hello"<<endl;
  }

  void disp(){
    cout<<"Hi\n";
  }

};

int main(){

ABC* b=(ABC*)malloc(sizeof(ABC));
int* q = new int[20];
ABC *a=new ABC();
b->disp();

cout<<b<<endl;
free(b);
delete b;
//a=NULL;
b->disp();
ABC();
cout<<b;
return 0;
}

output :

Hello
Hi
0x2abfef37cc20
Shady Aziza
  • 50,824
  • 20
  • 115
  • 113
-5

1.new syntex is simpler than malloc()

2.new/delete is a operator where malloc()/free() is a function.

3.new/delete execute faster than malloc()/free() because new assemly code directly pasted by the compiler.

4.we can change new/delete meaning in program with the help of operator overlading.

Nitesh
  • 303
  • 1
  • 5