7.8 why New/delete is required when malloc/free is available?
Malloc and free are standard library functions in C ++/C, and new/delete are operators in C ++. They can be used to apply for dynamic memory and release memory. For non-Internal data objectsMaloc/free cannot meet dynamic object requirements. The constructor must be automatically executed when the object is created, and the Destructor must be automatically executed before the object is extinct. Since malloc/free is a library function rather than an operator and is not controlled by the compiler, it is impossible to impose the tasks of executing constructor and destructor on malloc/free. Therefore, the C ++ language requires a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can clean up and release memory. Note that new/delete is not a database function.
First, let's take a look at how malloc/free and new/delete implement dynamic memory management of objects. See example 7-8.
Since the new/delete function completely covers malloc/free, why does C ++ not eliminate malloc/free?
This is because C ++ programs often call C functions, and C Programs can only use malloc/free to manage dynamic memory.
If you use free to release the "New Dynamic Object", this object may cause program errors because it cannot execute the destructor. If you use Delete to release the "dynamic memory applied by malloc", theoretically, the program will not go wrong, but the program is poorly readable. Therefore, new/delete must be paired, and the same applies to malloc/free.
7.9 What should I do if the memory is exhausted?
If a large enough memory block cannot be found when applying for dynamic memory, malloc and new will return a null pointer, declaring that the memory application failed. There are usually three ways to handle the "memory depletion" problem.
(1) judge whether the pointer is null. If yes, use the return statement to terminate the function immediately.For example:
Void func (void)
{
A * A = new;
If (A = NULL)
{
Return;
}
...
}
(2) judge whether the pointer is null. If yes, use exit (1) to terminate the entire program.For example:
Void func (void)
{
A * A = new;
If (A = NULL)
{
Cout <"Memory Exhausted" <Endl;
Exit (1 );
}
...
}
(3) set exception handling functions for new and malloc.For example, in Visual C ++, you can use the _ set_new_hander function to set your own exception handling function for new, or enable malloc to use the same exception handling function as new. For more information, see the C ++ user manual.