In C++, both malloc
and new
are used to allocate memory dynamically on the heap, but they differ in syntax, behavior, type safety, and features.
Dynamic memory allocation allows us to create variable or objects at runtime – the memory lives on the heap rather than the stack. Two primary ways to allocate heap memory in C++ are:
- The
malloc()
function (inherited from C) - The
new
operator (introduced in C++)
While they serves a similar purpose, their behaviors differ significantly.
Overview
new
Operator
new
in an C++ specific operator used to allocate memory dynamically and initialize objects by calling constructors.
int* ptr = new int(5); // Allocates memory and assigns value 5
malloc()
Function
malloc()
comes from C
(#include <cstdlib>
) and only allocates memory. It does not initialize objects or call constructors.
int* ptr = (int*) malloc(sizeof(int)); // Allocates memory, does not initialize
*ptr = 5;
Key Differences
Feature | malloc | new |
---|---|---|
Language | C (also used in C++) | C++ only |
Memory allocated on | Heap | Heap |
Syntax | ptr = (Type*)malloc(size) | ptr = new Type |
Return type | void* | Typed pointer |
Type safety | ❌ Unsafe (must cast) | ✅ Safe (no casting required) |
Constructor call | ❌ No | ✅ Yes |
Destructor call | ❌ No (free doesn't call dtor) | ✅ Yes (via delete ) |
Error handling | Returns NULL on failure | Throws std::bad_alloc on failure |
Deallocation | free(ptr); | delete ptr; |
Array allocation | malloc(n * sizeof(Type)) | new Type[n] |
Array deallocation | free(ptr); | delete[] ptr; |
Constructor/Destructor Support
One of the most important differences is that new
automatically calls the constructor of the object you are allocating, while malloc
does not.
class Demo {
public:
Demo() { std::cout << "Constructor called\n"; }
~Demo() { std::cout << "Destructor called\n"; }
};
int main() {
Demo* d1 = new Demo(); // Calls constructor
delete d1; // Calls destructor
Demo* d2 = (Demo*) malloc(sizeof(Demo)); // Just allocates memory
free(d2); // Destructor NOT called
}
Error Handling
malloc
Returns NULL
if memory cannot be allocated:
int* ptr = (int*) malloc(sizeof(int));
if (ptr == NULL) {
std::cerr << "Memory allocation failed\n";
}
new
Throws a std::bad_alloc
exception:
try {
int* ptr = new int;
} catch (const std::bad_alloc& e) {
std::cerr << "Allocation failed: " << e.what() << "\n";
}
Deallocating Memory
Allocation | Deallocation |
---|---|
malloc() | free() |
new | delete |
new[] | delete[] |
⚠️ Mixing malloc
with delete
or new
with free
is undefined behavior and can lead to crashes.
Extra
malloc
is an function whilenew
is an operator.new
can be overloaded.
QnA
What if malloc
is used to allocate a C++
object that has a constructor?
malloc only reserves raw memory. It does not:
- Call the constructor
- Initialize member variables
- Set up virtual tables (in case of polymorphic classes)
That can lead to undefined behavior if you start using the objects as it it were properly initialized.