Step into the minefield of C ++-C ++ memory management (III)

Source: Internet
Author: User
6. Why New/delete?

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 objects, maloc/free alone cannot meet the requirements of dynamic objects. 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 6.

Class OBJ
{
Public:
OBJ (void) {cout <"initialization" <Endl ;}
~ OBJ (void) {cout <"Destroy" <Endl ;}
Void initialize (void) {cout <"initialization" <Endl ;}
Void destroy (void) {cout <"Destroy" <Endl ;}
};
Void usemallocfree (void)
{
OBJ * A = (OBJ *) malloc (sizeof (OBJ); // apply for dynamic memory
A-> initialize (); // Initialization
//...
A-> destroy (); // clear the job
Free (a); // releases the memory.
}
Void usenewdelete (void)
{
OBJ * A = new OBJ; // apply for dynamic memory and initialize
//...
Delete A; // clear and release the memory
}

Example 6 How to Use malloc/free and new/Delete to manage the dynamic memory of Objects

The class OBJ function initialize simulates the constructor function, and the function destroy simulates the destructor function. In usemallocfree, because malloc/free cannot execute constructor and destructor, you must call the member functions initialize and destroy to complete initialization and clearing. The usenewdelete function is much simpler.

Therefore, we should not attempt to use malloc/free to manage the memory of dynamic objects. We should use new/Delete. Because the internal data type "object" does not have a process of construction and analysis, malloc/free and new/delete are equivalent to them.

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. 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.

The above (1) (2) method is the most common. If a function needs to apply for dynamic memory in multiple places, the method (1) is insufficient (it is troublesome to release the memory) and should be handled in the way (2.

A lot of people cannot bear to use exit (1). They asked, "Can the operating system solve the problem by itself without writing error handling programs ?"

No. In case of a "memory depletion" event, generally applications are no longer saved. If you do not use exit (1) to kill the program, it may kill the operating system. The truth is: if you do not kill a gangster, the gangster will commit more crimes before he dies.

There is a very important phenomenon to tell you. For 32-bit applications, no matter how malloc and new are used, it is almost impossible to cause "memory depletion ". In Windows 98, I wrote a test program using Visual C ++. See example 7. This program will run endlessly and will not be terminated at all. Because the 32-bit operating system supports "virtual storage" and the memory is used up, the hard disk space is automatically replaced. I only heard the sound of the hard drive. Window 98 was so tired that it didn't respond to the keyboard or mouse.

I can conclude that for 32-bit or more applications, the "memory used up" error handler is useless. Now, UNIX and Windows programmers are happy with this: the error handler does not work, and I will not write it, saving a lot of trouble.

I don't want to mislead readers. I must emphasize that without error handling, the quality of the program will be poor, and never be compromised.

Void main (void)
{
Float * P = NULL;
While (true)
{
P = new float [1000000];
Cout <"Eat memory" <Endl;
If (P = NULL)
Exit (1 );
}
}

Example 7 try to exhaust the operating system memory

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.