![]() |
VOOZH | about |
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() (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.
pointer = (data_type*)malloc(size_in_bytes);
Value: 100
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.
pointer = new data_type;
Value: 100
| 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 |