- Memory Allocation and Initialization
Both malloc and new allocate memory on the heap, but:
- malloc only allocates memory without initialization.
- new allocates memory and initializes it.
Examples:
- new int(10) → Allocates an int and initializes it to 10.
- new int[10]() → Allocates an int array of size 10 and initializes all elements to 0.
- Usage and Return Type
Code examples:
int *p1 = (int *)malloc(sizeof(int)); // malloc: cast required
int *p2 = new int(2); // new: initializes single int to 2
int *p3 = new int[100](0); // new: array of 100 ints (all 0)
Execution output:
1
2
3
- malloc is a function:
- Requires specifying the number of bytes (e.g., malloc(100) for 100 bytes).
- Returns a void* pointer (needs explicit casting to the target type).
- new is an operator:
- Requires specifying the data type (not byte count).
- Returns a pointer of the specified type directly (no casting needed).
- Error Handling and Underlying Logic
- malloc returns null if allocation fails.
- new throws a bad_alloc exception on failure (must be caught to check success).
- new internally calls operator_new, which uses malloc for allocation but adds initialization. For classes, this means calling the constructor.
- Memory Deallocation
- Memory from malloc is freed with free().
- Memory from new is freed with:
- delete for single objects (e.g., delete p2;).
- delete[] for arrays (e.g., delete[] p3;).
- Allocation Variants
- malloc has only one allocation method.
- new has four variants:
- Ordinary new
- const new
- Placement new (allocates at a specific memory address)
- nothrow new (returns null instead of throwing exceptions on failure)
你可以直接修改上述内容中的文本、代码示例或格式,根据需要调整细节。