Dynamic Memory Management --- new & amp; delete, dynamic memory --- new

Source: Internet
Author: User

Dynamic Memory Management --- new & delete, dynamic memory --- new
Dynamic Memory Management


A Dynamic Object (heap object) is an object created by using the new operator in the dynamic memory during running of a program.
Because the user created it by using the new operator, the user is also required to use the delete operator to release it, that is, the user must manage the dynamic memory on his own.


There are usually three partitions in the computer memory data zone, namely the static data zone, heap zone, and worker zone.


1. The program allocates a static data storage area for static variables and static objects during compilation. Variables or objects stored in the static data area exist throughout the entire running period of the program,
Their life cycles run throughout the entire program. For example, global variables and static variables are all stored in the static data zone.


2. When a function is called, the local variables and formal parameters in the function are allocated to the storage unit in the memory area. The life cycle of these variables is the same as the execution time of the function.
When function execution ends, the storage units that store these variables are automatically released, and the lifecycle of these variables ends.
Because the size of the swap area is generally limited, the number of variables that can be stored in the SWAp area at the same time is limited.
Because the life cycle of variables stored in the primary area is short, the utilization rate in the primary area is very high, and it can become the storage space for new variables.


3. When the new operator is executed, the system automatically allocates storage space in the dynamic memory space. The dynamic memory is located in the heap zone. It is the only storage space that can be controlled by the programmer for the lifetime.
When the program is running, the programmer can use new to apply for dynamic memory space, but when it is not in use, the programmer must use delete to release the space (release the memory ).
Therefore, the program has a very high probability of errors in this part.


The operators used to manage dynamic memory space are new and delete, and new [] and delete [].


Use the malloc () and free () functions in C to apply for allocation and release of dynamic memory space.
C ++ uses the new and delete operators to allocate and release dynamic memory space.


The new operator can automatically calculate the size of the requested space, while the malloc () function must be pointed out by the programmer.


# Include <iostream> using namespace std; int main () {char * p1; int * p2; int * p3 = new int (14 ); int * p4 = new int [3]; p1 = new char; // a new integer, and assign the address of this integer to p1p2 = new int (10 ); // a new integer with an initial value of 200, and assigns the address of this integer to p2 * p1 = 97; for (int I = 0; I <3; I ++) {cin> * (p4 + I);} cout <* p1 <endl; cout <* p2 <endl; cout <* p3 <endl; for (int I = 0; I <3; I ++) {cout <* (p4 + I) <"";} cout <endl; delete p3; delete p2; delete p1; delete [] p4; p1 = NULL; p2 = NULL; p3 = NULL; p4 = NULL; system ("pause"); return 0 ;}

Note:
1. When the system cannot meet the dynamic memory allocation request, it will return NULL. Therefore, after new execution, you must determine whether the returned pointer value is NULL. If yes, the dynamic memory allocation is unsuccessful.
You can continue subsequent operations only when the returned value is not NULL.
If you perform memory operations on an unapplied pointer, the system may crash.

2. delete can only be used to release the dynamic memory space applied for by new. Otherwise, the dynamic memory space applied by new must be released by delete.

Delete and new must have a corresponding relationship.
3. After the delete operation, the memory space pointed to by the pointer is released, and the pointer variable pointing to the dynamic memory area does not change itself because of the delete operation.
4. After the delete operation, if you do not perform any processing on the pointer variable, the "pointer suspension" will occur ";

5. operate on the memory space without initialization after the pointer variable is declared. A "wild pointer" may be created ";

6. Pay special attention to pointer and dynamic memory:
The pointer disappears, which does not mean that the dynamic memory it points to will be automatically released and automatically extinct;
When the dynamic memory is released, it does not mean that the pointer variable pointing to the dynamic memory will die out or automatically become NULL;


Do the following to prevent errors:
1. Define the initialization of pointer variables at the same time. If it is not initialized, it must be set to NULL to avoid pointing the pointer to an uncertain place and causing misoperation. This is very dangerous.
Once it is set to NULL, misuse of it will not cause too many problems;
2. After the delete pointer, set it to NULL immediately. Even a local pointer variable that is about to die out immediately can be set to NULL. Developing good habits is an effective way to avoid mistakes;
3. When the pointer points to an array, be sure to avoid cross-border pointer operations;
4. Avoid using pointers to transmit swap memory, and avoid returning the address of a local variable or local object that is about to die out automatically.
Both local variables and local objects in memory cannot survive across functions. Pay attention to their lifecycles.

Note: delete:

# Include <iostream> using namespace std; int main () {int I, * pi1 = & I, * pi2 = nullptr; double * pd = new double (33 ), * pd2 = pd; int ii = 0; // delete I; // error, I is not a pointer cout <ii ++ <endl; // delete pi1; // definition: pi1 points to a local variable and no dynamic memory cout is allocated <ii ++ <endl; delete pi2; // correct: release a null pointer cout <ii ++ <endl; delete pd; // correct cout <ii ++ <endl; // delete pd2; // undefined ,: the pointed memory has been released cout <ii ++ <endl; system ("pause"); return 0 ;}


For a delete I request, the compiler generates an error message because it knows that I is not a pointer. Errors generated by executing delete pi1 and pd2 are more potentially harmful: In general, the compiler cannot tell whether a pointer points to static and dynamically allocated objects. At the same time, the compiler cannot tell whether the memory pointed to by a pointer has been released.


The memory of the new dynamic application is the same as that of the directly defined array in memory processing.

Array is actually a pointer, but the pointer system has allocated a memory address for it and will automatically recycle it at the end of the variable cycle. If the pointer is used, the int * p system will not allocate memory for p. In this case, p is a wild pointer. You can use p = new int [10] to allocate memory for it, pay attention to the use of delete for recovery, or memory leakage may occur.

C language: the memory is dynamically allocated. What is the difference between malloc and new? Is the memory allocated by malloc continuous? Is the memory allocated by new discontinuous?

For built-in types, the functions of malloc and new are the same, and the allocated space is continuous.
When new is used in a custom type such as class, the class constructor is automatically called. When delete is used, the class destructor is automatically called. If free is used, the operation cannot be performed.

New is the keyword in C ++.
If you use C ++, we recommend that you use new

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.