malloc() vs new (original) (raw)

Last Updated : 5 Jun, 2026

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()

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.

Syntax

pointer = (data_type*)malloc(size_in_bytes);

C++ `

#include #include using namespace std;

int main() { int* ptr = (int*)malloc(sizeof(int));

*ptr = 100;

cout << "Value: " << *ptr;

free(ptr);

return 0;

}

`

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.

Syntax

pointer = new data_type;

C++ `

#include using namespace std;

int main() { int* ptr = new int;

*ptr = 100;

cout << "Value: " << *ptr;

delete ptr;

return 0;

}

`

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 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