Understanding memory allocation in C++: ‘malloc’ vs ‘new’
Malloc:
‘malloc‘ functions are inherited from C and are used to allocate a block of memory of a specified size. Here are some properties of malloc:
- malloc does not call any constructor.
- It only allocates memory but does not initialize it.
- Explicit casting is required to assign a return value to a pointer of any specific type because the return value of malloc is void.
Example:
The following code demonstrates a common pattern for dynamic memory allocation, especially when working with a single object using malloc :
int* m = (int*)malloc(sizeof(int));
The following example illustrates a common pattern for dynamically allocating memory, specifically for an array of 10 integers.
int* arr = (int*)malloc(10 * sizeof(int));