Detailed description of the heap, stack, and static storage areas

Source: Internet
Author: User

First, the basic structure of memory

The programmable internal presence is basically divided into the following parts: Static storage, heap, and stack areas. They have different functions and different ways of using them.

Static storage: Within the time the program is compiled, it is already allocated, and the entire running period of the program exists in this block. It mainly stores static data, global data, and constants.

Stack area: When executing a function, the storage units of local variables within the function can be created on the stack, which are automatically freed when the function is executed at the end. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.

Heap area: Also known as dynamic memory allocation. The program uses malloc or new to request any size of memory at run time, and the programmer is responsible for freeing the memory with free or delete when appropriate. The lifetime of dynamic memory can be determined by us, and if we do not release the memory, the program will release the dynamic memory at the end. However, good programming habits are: If a dynamic memory is no longer used, it needs to be released, otherwise, we think there is a memory leak phenomenon.

Difference between the two and three

Let's take a look at the code snippet to see how the three parts of memory need to be manipulated and different, and where to pay attention.

Example one: static storage and Stack area

char* p = "Hello World1"; Char a[] = "Hello World2"; P[2] = ' A '; A[2] = ' A '; char* p1 = "Hello World1";

This program is error, error occurs in p[2] = ' A ' This line of code, for what, is the variable p and variable array A all exist in the stack (any temporary variables are in the stack, including the variables defined in the main () function). However, the data "Hello World1" and the data "Hello World2" are stored in different regions.

Because the data "Hello World2" exists in the array, this data is stored in the stack area, and there is no problem with its modification. Because the pointer variable p is only able to store the address of a storage space, the data "Hello World1" is a string constant, so it is stored in a static storage area. Although through p[2] you can access the third unit of data in the static store, the unit of storage where the character ' L ' resides. However, because the data "Hello World1" is a string constant, it cannot be changed, so a memory error is reported when the program is run. Also, if the output of P and P1 at this time, it will be found that the address stored in P and P1 is exactly the same. In other words, only one copy of the same data is kept in the data area.

Example two: Stack area and heap area

Char* F1 () {char* p = NULL;    Char A;    p = &a; return p;}    char* F2 () {char* p = null:p = (char*) new char[4]; return p;}

Both of these functions return the address of a storage space, what is the difference between them? The F1 () function returns a storage space, but this space is a temporary space. In other words, this space has only a short life cycle, and its life cycle at the end of the function F1 () call loses its life value, namely: this space is freed. So, when you call the F1 () function, if you have the following statement in your program:

char* p;p = f1 (); *p = ' a ';

At this point, the compilation does not report an error, but an exception error occurs when the program is run. Because you're working on memory that should not be manipulated (that is, the storage space that has been freed). However, in contrast, the F2 () function does not have any problems. Because the new command is to request storage space in the heap, once the application succeeds, the memory will persist unless you delete it or terminate the program. It can also be understood that heap memory is a shared unit that can be accessed by multiple functions together. Heap memory is a good choice if you need to have more than one data return but no way. But be sure to avoid the following things happening:

void F () {... char * p;    p = (char*) new char[100]; ...}

This program does a very pointless thing and can bring great harm. Because, although the heap memory is applied, p holds the first address of the heap memory. However, this variable is a temporary variable and the p variable disappears when the function call ends. That is, there is no more variable to store the first address of this heap of memory, and we will never be able to use that heap of memory again. However, this heap of memory has always been identified by your use (because you did not delete it until the end of the program, so this heap of memory has been identified by the owner as the current program), and other processes or programs are not available. We refer to this unethical "rogue behavior" (which we don't use, but do not allow others) to call a memory leak. This is our C + + Programmer's taboo!! Please make sure that you avoid this thing from happening.

In summary, the biggest difference between heap, stack, and static storage is that the life cycle of the stack is short. However, the life cycle of the heap and static stores is equivalent to the life of the program (if you do not delete the heap memory in the middle of the program run), we refer to this variable or data as a global variable or data. However, the memory space usage of the heap area is more flexible because it allows you to free it at any time when it is not needed, while the static storage will always exist throughout the lifetime of the program.

Three, heap area, stack area and static storage area use rule

After rule 1 has requested memory with malloc or new, you should immediately check that the pointer value is NULL. Prevents the use of memory with a pointer value of NULL.

Rule 2 Do not forget to assign an initial value to both arrays and dynamic memory. Prevents memory that is not initialized from being used as the right value.

"Rule 3" avoids array or pointer subscript out of bounds, especially beware of "more 1" or "less 1" operations.

"Rule 4" the request and release of dynamic memory must be paired to prevent a memory leak.

"Rule 5" after releasing memory with free or delete, immediately set the pointer to NULL to prevent the "wild pointer" from being produced.

Iv. discussion of Heap and stack

Management method:

The resources in the heap are controlled by the programmer (easy to generate memory leak).

Stack resources are automatically managed by the compiler without manual control.

System response:

For the heap, you should know that the system has a list of idle memory address, when the system receives a program request, traverse the list, look for the first space is larger than the application space of the heap node, delete the idle node linked list of the node, The node space is allocated to the program (most systems record the size of this allocation at the first address of the memory space, so that delete can properly free up the memory space, and the system will re-place the extra parts into the idle list).

For the stack, as long as the remaining space on the stack is larger than the requested space, the system provides memory for the program, otherwise the exception prompt stack overflow.

Space size:

Heap is a discontinuous area of memory (because the system uses a linked list to store free memory addresses, nature is not continuous), the heap size is limited by the effective virtual memory in the computer system (32bit system theoretically 4G), so the heap space is more flexible, larger.

Stack is a contiguous area of memory, the size of the operating system is scheduled, Windows stack size is 2M (there is 1M, at compile time, VC can be set).

Fragmentation issues:

For heaps, frequent new/delete can cause a lot of fragmentation, which reduces program efficiency.

For stacks, it is an advanced post-out queue that corresponds to and from one by one and does not produce fragmentation.

Direction of growth:

Heap upward, increasing in the direction of the high address.

Stack down, increasing in the low address direction.

Allocation method:

Heaps are dynamically allocated (there is no statically allocated heap).

Stacks have static allocations and dynamic allocations, static allocations are done by compilers (such as local variable allocations), and dynamic allocations are allocated by the ALLOCA function, but the dynamically allocated resources of the stack are freed by the compiler without the programmer's implementation.

Allocation efficiency:

The heap is provided by the C + + function library and the mechanism is complex. So the heap is much less efficient than the stack.

The stack is the data structure provided by the machine system, the computer supports the stack at the bottom, allocates the special register storage stack address, and the stack operation has the special instruction.


Detailed description of the heap, stack, and static storage area

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.