new — C++ operator. malloc — C function.
new:
1// Allocate single object2int* ptr = new int(10); // Initialize with 1034// Allocate array5int* arr = new int[5]; // No initialization6int* arr2 = new int[5]{1, 2, 3, 4, 5}; // C++1178// Calls constructor9MyClass* obj = new MyClass();1011// Returns typed pointer12int* p = new int; // int*1314// Deallocate15delete ptr;16delete[] arr;
malloc:
1#include <cstdlib>23// Allocate memory4int* ptr = (int*)malloc(sizeof(int));56// Array7int* arr = (int*)malloc(5 * sizeof(int));89// No constructor call!10MyClass* obj = (MyClass*)malloc(sizeof(MyClass));1112// Returns void*13void* p = malloc(100);1415// Deallocate16free(ptr);
Key differences: