malloc() and new are used for dynamic memory allocation in C++, allowing memory to be allocated during program execution. Although both allocate memory from the heap, they differ in functionality, type safety, and object handling.
- malloc() is a C library function, while new is a C++ operator.
- new is generally preferred in C++ because it supports constructors and type safety.
malloc()
malloc() (Memory Allocation) is a standard C library function used to allocate a specified amount of memory at runtime. It allocates raw memory and returns a pointer to the allocated block.
- Defined in the <cstdlib> header file.
- Allocates memory but does not initialize it.
- Does not call constructors for objects.
Syntax
pointer = (data_type*)malloc(size_in_bytes);
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int* ptr = (int*)malloc(sizeof(int));
*ptr = 100;
cout << "Value: " << *ptr;
free(ptr);
return 0;
}
Output
Value: 100
new Operator
The new operator is a C++ feature used to dynamically allocate memory for variables and objects. It automatically returns the correct pointer type and invokes constructors when creating objects.
- No explicit type casting is required.
- Calls constructors for objects automatically.
- Memory is released using the delete operator.
Syntax
pointer = new data_type;
#include <iostream>
using namespace std;
int main() {
int* ptr = new int;
*ptr = 100;
cout << "Value: " << *ptr;
delete ptr;
return 0;
}
Output
Value: 100
malloc() vs new
| Feature | malloc() | new |
|---|---|---|
| Type | A library function | A C++ operator |
| Language Support | Available in C and C++ | Available only in C++ |
| Header File | Requires <cstdlib> | No header required |
| Return Value | Returns void* pointer | Returns typed pointer |
| Type Casting | Explicit type casting required | No type casting required |
| Constructor Call | Does not call constructors | Calls constructors automatically |
| Initialization | Allocates uninitialized memory | Can initialize memory during allocation |
| Memory Release | Memory is freed using free() | Memory is released using delete |
| Object Support | Not suitable for object creation | Suitable for object creation |
| Error Handling | Returns NULL on failure | Throws bad_alloc on failure |
| Type Safety | Less type-safe | More type-safe |
| Usage in Modern C++ | Rarely used | Recommended approach |