please descript the difference with malloc of c and new of c++
时间: 2024-12-10 20:49:19 浏览: 16
In C, memory allocation is typically done using the `malloc` function, which is part of the C standard library. Here's how it works:
**C - malloc()**
```c
void* malloc(size_t size);
```
`malloc` allocates a block of uninitialized memory of the specified size in bytes. If successful, it returns a pointer to the allocated memory; otherwise, it returns `NULL`. The programmer is responsible for managing this memory by calling `free()` when no longer needed.
**C++ - new**
In C++, memory allocation is performed using the `new` keyword, which is part of the language itself. It also involves dynamic memory allocation but provides additional safety features:
**C++ - new**
```cpp
void* operator new(size_t size);
```
`new` does similar work as `malloc`, allocating memory and returning a pointer. However, C++ adds constructors for objects (if applicable), meaning that if you allocate an object with `new`, its constructor will be called automatically upon allocation. Additionally, C++ provides `delete` to deallocate the memory when no longer needed:
```cpp
void operator delete(void* ptr);
```
**Differences:**
1. **Error handling:** C++'s `new` includes bounds checking, while `malloc` may not. This means `new` can throw exceptions if memory cannot be allocated, whereas `malloc` silently fails.
2. **Resource management:** In C, you must manually call `free` to release memory. In C++, this is handled implicitly with `delete` or `delete[]` for arrays.
3. **Memory alignment:** C++ ensures proper alignment for certain types, while `malloc` does not guarantee alignment.
4. **Object construction/destruction:** C++'s `new` supports automatic construction and destruction of objects, which is not possible with `malloc`.
阅读全文