What is the difference between "new" and "malloc" and "calloc" in C++? [duplicate]
new
and delete
are C++ specific features. They didn't exist in C. malloc
is the old school C way to do things. Most of the time, you won't need to use it in C++.
-
malloc
allocates uninitialized memory. The allocated memory has to be released withfree
. -
calloc
is likemalloc
but initializes the allocated memory with a constant (0). It needs to be freed withfree
. -
new
initializes the allocated memory by calling the constructor (if it's an object). Memory allocated withnew
should be released withdelete
(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, it's more modern and less prone to errors.
new
/delete
+ new[]
/delete[]
:
-
new
/delete
is the C++ way to allocate memory and deallocate memory from the heap. -
new[]
anddelete[]
is the C++ way to allocate arrays of contiguous memory. - Should be used because it is more type safe than
malloc
- Should be used because it calls the constructor/destructor
- Cannot be used in a
realloc
way, but can use placement new to re-use the same buffer of data - Data cannot be allocated with
new
and freed withfree
, nordelete[]
malloc
/free
+ family:
-
malloc
/free
/family is the C way to allocate and free memory from the heap. -
calloc
is the same asmalloc
but also initializes the memory - Should be used if you may need to reallocate the memory
- Data cannot be allocated with
malloc
and freed with delete nor delete[]
Also see my related answer here
-
new
allocates and calls to ctor (the order is unspecified),delete
the dtor and frees the memory allocated by a call to new -
malloc
only allocates some memory, andfree
deletes memory allocated bymalloc
-
new
may be implemented usingmalloc
(not required though by the standard) -
calloc
does the same thing asmalloc
and also zero-initialises the newly allocated memory
As other posts have pointed out: malloc
/free
is part of C++ to be compatible with C.
Also see: Stroustrup: new vs malloc
You don't need anything other than new. It is a complete replacement for malloc in C++.
As for the difference: Malloc just allocates memory. New allocated memory and calls the constructors. Likewise free just releases the memory. Delete releases the memory and calls the destructor.
A word of warning: Don't mix the two idioms. The results are undefined.