What if the memory is exhausted?

Source: Internet
Author: User
The great Bill Gates once said:

   640 K ought to be enough for everybody-Bill Gates 1981

What 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

8. Usage of malloc/free

The following is a prototype of the malloc function:

Void * malloc (size_t size );

Use malloc to apply for an integer-type memory with a length. The program is as follows:

Int * P = (int *) malloc (sizeof (INT) * length );

We should focus on two elements: "type conversion" and "sizeof ".

* The type returned by malloc is void *. Therefore, you must explicitly convert the type when calling malloc and convert void * to the required pointer type.

* The malloc function does not recognize the type of memory to be applied for. It only cares about the total number of bytes in the memory. We usually cannot remember the exact number of bytes for int, float, and other data types. For example, the int variable is 2 bytes in a 16-bit system and 4 bytes in a 32-bit system, and the float variable is 4 bytes in a 16-bit system, it is also 4 bytes in 32 bits. It is best to use the following program for a test:

Cout <sizeof (char) <Endl;
Cout <sizeof (INT) <Endl;
Cout <sizeof (unsigned INT) <Endl;
Cout <sizeof (long) <Endl;
Cout <sizeof (unsigned long) <Endl;
Cout <sizeof (float) <Endl;
Cout <sizeof (double) <Endl;
Cout <sizeof (void *) <Endl;

Using the sizeof operator in malloc's "()" is a good style, but be careful when we sometimes get dizzy and write P = malloc (sizeof (p )) such a program.

* The prototype of function free is as follows:

Void free (void * memblock );

Why isn't the free function as complicated as the malloc function? This is because the pointer p type and the memory capacity it refers to are known in advance, and the statement free (p) can correctly release the memory. If P is a null pointer, no matter how many times the free P operation will fail. If P is not a null pointer, the free operation on P will cause a program running error.

New/deleteKey Points of useThe new operator is much easier to use than the malloc function, for example:

Int * P1 = (int *) malloc (sizeof (INT) * length );
Int * P2 = new int [length];

This is because new has built-in sizeof, type conversion, and type security check functions. For non-Internal data objects, new completes initialization while creating dynamic objects. If an object has multiple constructors, the new statement can also have multiple forms. For example

Class OBJ
{
Public:
OBJ (void); // a constructor without Parameters
OBJ (int x); // constructor with a parameter
...
}
Void test (void)
{
OBJ * A = new OBJ;
OBJ * B = new OBJ (1); // The initial value is 1.
...
Delete;
Delete B;
}

If you use new to create an object array, you can only use the non-parameter constructor of the object. For example

OBJ * objects = new OBJ [100]; // creation of 100 dynamic objects cannot be written
OBJ * objects = new OBJ [100] (1); // create 100 dynamic objects and assign initial value 1
When releasing an object Array Using Delete, do not lose the symbol '[]'. For example

Delete [] objects; // correct usage
Delete objects; // incorrect usage

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.