Home > Article > Backend Development > The difference between malloc and new in c++
The main difference between malloc and new in C is that the memory allocated by malloc needs to be released manually, while the memory allocated by new is released automatically. Malloc returns NULL if allocation fails, and throws an exception if new allocation fails. New automatically initializes the memory allocated, and the memory allocated by malloc needs to be initialized manually. new supports advanced features, such as array allocation, custom allocator, etc., malloc does not support it.
The difference between malloc and new in C
malloc and new are both commonly used memory allocation functions in C , but there are some key differences between them.
1. Syntax
<code class="cpp">void *malloc(size_t size); void *new(size_t size, std::nothrow_t = nullptr);</code>
2. Return value
std::bad_alloc
exception will be thrown. 3. Memory management
to release.
4. Initialization
In general, malloc and new are both memory allocation functions, but new is safer and easier to use, and can automatically initialize and handle exceptions . For simple memory allocation scenarios, malloc can be used, but for complex scenarios that require more features, new is recommended.
The above is the detailed content of The difference between malloc and new in c++. For more information, please follow other related articles on the PHP Chinese website!