malloc() vs new

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

C++
#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;

C++
#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

Featuremalloc()new
TypeA library functionA C++ operator
Language SupportAvailable in C and C++Available only in C++
Header FileRequires <cstdlib>No header required
Return ValueReturns void* pointerReturns typed pointer
Type CastingExplicit type casting requiredNo type casting required
Constructor CallDoes not call constructorsCalls constructors automatically
InitializationAllocates uninitialized memoryCan initialize memory during allocation
Memory ReleaseMemory is freed using free()Memory is released using delete
Object SupportNot suitable for object creationSuitable for object creation
Error HandlingReturns NULL on failureThrows bad_alloc on failure
Type SafetyLess type-safeMore type-safe
Usage in Modern C++Rarely usedRecommended approach
Comment