C + + memory management

Source: Internet
Author: User

In C + +, memory is mainly divided into 5 storage areas:

Stack: Local variables, function parameters, etc. are stored in the area, and are automatically allocated and freed by the compiler. Stack belongs to the data structure of computer system, the stack out stack has corresponding computer instruction support, and allocates the address of special register storage stack, the efficiency is high, the memory space is continuous, but the memory space of the stack is limited.

Heap: Requires a programmer to manually assign and release (New,delete), which is a dynamic allocation method. Memory space is almost unlimited and memory space is not contiguous, resulting in memory fragmentation. The operating system has a linked list that records space memory, iterates through the list when a memory request is received, finds the first heap node with a space greater than the requisition space, assigns the node to the program, and removes the node from the linked list. Typically, the allocated memory size is recorded at the first address of the memory space for the delete to free the memory space.

Global/Static storage: Global variables, static variables allocated to the zone, to the end of the program is automatically released, including the data segment (global initialization area) and BBS segment (Global uninitialized segment). Where the initialized global variables and static variables are stored in the data segment, the uninitialized global variables and static variables are stored in the BBS segment. BBS segment Features: The BBS segment is automatically zeroed before the program executes, so uninitialized global variables and static variables become 0 before the program executes.

Literal constant area: Holds constants, and does not allow modification. Released by the system after the program is finished.

Program code area: binary code for stored programs

Three ways to use the storage area:
1) static storage area (static memory)

Global variables, static variables, and static class members are stored in the zone, allocated during compilation, and lifetime to the end of the program. Objects stored in this area are initialized only once, and the address is fixed during program run time.

2) automatic storage area (autormatic memory)

Local variables, function parameters, etc. are stored in this area and are automatically assigned and freed by the compiler

3) Free Storage area

Manually allocating and freeing memory by programmers (New,delete)

The difference between heap and stack:

1) Space size: The memory space of the stack is continuous, the size of the space is usually predetermined, that is, the stack top address and the maximum space is determined, and the heap of memory space is not contiguous, by a record space of the linked list is responsible for management, so the memory space is almost unlimited, under 32-bit system, Memory space up to 4G

2) Management method: The stack is automatically allocated and freed by the compiler, and the heap requires the programmer to manually allocate and release, if forget delete, prone to memory leaks.

3) The growth direction is different: for the stack, he is to the memory address of the direction of growth, which is why the memory space of the stack is limited, and the heap is in the direction of increasing memory address growth

4) Fragmentation problem: Because the stack of memory space is continuous, the advanced way to ensure that no fragmented space, and the heap allocation method is each time in the idle list to traverse to the first node larger than the request space, each allocation of space is generally not exactly equal to the requested memory size, Frequent new operations are bound to generate large amounts of space debris

5) Allocation efficiency: The stack is the data structure provided by the machine system, the computer will support the stack at the bottom, the stack stack is executed by the special instruction, so the efficiency is high. The heap is provided by the C + + function library, when the application space needs to follow a certain algorithm to search for a sufficient amount of memory space, when there is not enough space, additional processing is required, so the efficiency is low.

A few things to note when using memory:

1) When requesting memory with new and malloc, check that the memory is allocated successfully before use

Char *p=new char[10];if (p==null) return;

2) initialize before using memory

3) in the operation of memory, to prevent the cross-border, such as array operation to pay attention to the subscript range

4) for dynamically allocated memory, be sure to release it manually, or the program will lose a portion of memory every time it runs, causing a memory leak

5) to prevent memory release after continuing to use it, mainly in the following three cases:

A. The object invocation relationship in the program is too complex, it is difficult to figure out whether an object has freed the memory, at this time should redesign the data structure, fundamentally solve the chaos of object management.

B. The return statement of the function is incorrectly written, and be careful not to return a pointer or reference to "stack memory" because the memory is automatically destroyed at the end of the function body.

C. After releasing memory with free or delete, the pointer is not set to null. Causes the "wild pointer" to be produced.

Wild pointer:"Wild pointer" is not a null pointer, it is a pointer to "garbage" memory. It is generally not wrong to use a null pointer because it is easy to judge with an if statement. But a "wild pointer" is dangerous, and the IF statement does not work on it.

There are three main causes of the "Wild Hands" :

(a) The pointer variable is not initialized. Any pointer variable that has just been created does not automatically become a null pointer, and its default value is random, and it can be arbitrary. Therefore, the pointer variable should be initialized at the same time it is created, either by setting the pointer to null or by pointing it to legitimate memory.

char *p;   At this point P is the wild pointer

(b) After the pointer p is free or deleted, it is not set to NULL, and the person mistakenly thinks that p is a valid pointer.

Char *p=new char[10];  Points to the first address of the memory allocated in the heap cin>> p;delete []p; P re-becomes wild pointer

(c) Pointer manipulation goes beyond the scope of the variable.

Char *p=new char[10];  Points to the first address of the memory allocated in the heap cin>> p;cout<<* (p+10);  May output unknown data

6) Note points of the pointer:

A. Pointer to a constant store object

Char *p= "ABC";

P points at this point to a string constant that cannot write to the contents of *p, such as srtcpy (P,s), because the contents of P are "ABC" string constants, which are stored in a constant store, but can be manipulated against pointer p to point to other memory spaces.

B. Resource leaks

Char *p=new char[3]; Allocate three character space, p points to that memory space

p= "AB";//when P points to the constant "AB" instead of the memory space allocated by the new char, causing a resource leak

delete []p; Release The Times wrong

C. Memory out of Bounds

Char *p=new char[3]; Allocate three character space, p points to that memory space

strcpy (P, "ABCD"); The ABCD is stored in the allocated memory space due to strlen ("ABCD") =4>3, which crosses the

delete []p; Error when releasing

Note: p= "AB" and strcpy (p, "ab"), meaning different, the former pointer p points to the constant "AB" storage area of the first address, changed the first point of P to the new application of the memory space, and the latter is to assign "AB" to the new application of the memory space;

About pointers specific look: http://www.cnblogs.com/mrlsx/p/5419030.html

C + + memory management

Related Article

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.