C and C + + Storage area detailed (stack, heap, global ...) )

Source: Internet
Author: User
Tags stack pop
A. Divided into these storage areas in C
1. Stack-Automatically allocate release by compiler
2. Heap-typically released by programmers, if the programmer does not release, the program may end up being recycled by the OS
3. Global zone (static area), global variables and static variables are stored in a piece of the initialization of global variables and static variables in a region, uninitialized global variables and uninitialized static variables in another adjacent area. -Program End Release
4. There is also a special place for constants. -Program End Release

Variables defined in the function body are usually on the stack, with malloc, Calloc, realloc, and other functions allocated to the memory are allocated on the heap. The global quantity is defined in all functions, and the static modifier is added to the global area (static region), and the static variable defined in the body of all functions is valid in the file and cannot be used for other files. A static representation defined in a function body is only valid in the body of the function. In addition, a string such as "ADGFDF" in a function is stored in a constant area. Like what:
int a = 0; Global initialization Area
Char *p1; Global uninitialized Zone
void Main ()
{
int b; Stack
Char s[] = "ABC"; Stack
Char *p2; Stack
Char *p3 = "123456"; 123456{post.content} in the constant area, p3 on the stack
static int c = 0; Global (static) initialization area
P1 = (char *) malloc (10); Allocated 10 bytes of area in the heap area
P2 = (char *) malloc (20); Allocated 20 bytes of area in the heap area
strcpy (P1, "123456");
123456{post.content} is placed in a constant area, and the compiler might optimize it with the "123456" that P3 points to.
}

Two. In C + +, the memory is divided into 5 areas, they are the heap, stack, free storage area, global/static storage and constant storage area
1. Stacks are those that are allocated by the compiler at the time of need, and are automatically aware of variables when they are not needed. The variables inside are usually local variables, function parameters, and so on.
2. Heap, that is, those allocated by the new memory block, their release compiler does not go to the tube, by our application to control, generally a new will correspond to a delete. If the programmer is not released, the operating system will automatically recycle after the program finishes.
3. Free storage, which is the memory block allocated by malloc, he and the heap are very similar, but it is to use free to end their lives.
4. Global/static storage, global variables and static variables are assigned to the same memory, in the previous C language, the global variables are divided into initialized and uninitialized, in C + + without this distinction, they share the same memory area.
5. Constant storage, this is a special storage area, they hold a constant, not allowed to modify (of course, you have to pass improper means can also modify)

Three. Talking about the relationship and difference between heap and stack
Specifically, modern computers (serial execution mechanisms) directly support the stack's data structure at the bottom of the code. This manifests in, has the specialized registers to point to the stack address, has the specialized machine instruction completes the data to stack the operation. This mechanism is characterized by high efficiency, limited data support, general integer, pointers, floating-point numbers and other systems directly supported data types, does not directly support other data structures. Because of this feature of the stack, the use of the stack in the program is very frequent. The invocation of a child program is done directly using the stack. The call instruction in the machine implicitly pushes the return address into the stack and then jumps to the subroutine address, while the RET instruction in the subroutine implicitly pops the return address from the stack and jumps to the operation. The automatic variable in C + + is an example of using the stack directly, which is why the automatic variable of the function automatically fails when the function returns.

Unlike stacks, the data structure of a heap is not supported by the system (whether it is a machine system or an operating system), but is provided by a function library. The basic Malloc/realloc/free function maintains a set of internal heap data structures. When a program uses these functions to get new memory space, this set of functions first attempts to find the available memory space from the internal heap, if there is no memory space to use, then try to use system to dynamically increase the memory size of the program data segment, the new allocated space is first organized into the internal heap, It is then returned to the caller in the appropriate form. When the program frees allocated memory space, the memory space is returned to the internal heap structure and may be appropriately processed (such as merging other free space into larger free space) to better fit the next memory allocation request. This complex allocation mechanism is actually equivalent to a memory allocation buffer pool (cache), using this set of mechanisms for several reasons:
1. System calls may not support any memory allocations of any size. System calls in some systems support only memory requests that are fixed in size and their multiples (allocated by page), which can be wasteful for a large number of small memory categories.
2. System calls to request memory can be costly. System calls may involve conversion of user state and kernel mentality.
3. A memory allocation that is not managed can easily cause memory fragmentation under a large amount of complex memory allocation and release operations.

Stacks vs. Stacks
From the above knowledge, the stack is the function of the system, characterized by fast and efficient, the disadvantage is limited, the data is not flexible; the stack is function library provides the function, the characteristic is nimble convenient, the data adapts the surface to be broad, but the efficiency has certain reduction. The stack is the system data structure, is unique to the process/thread, the heap is the function library internal data structure, not necessarily unique. Memory for different heap allocations cannot interoperate with each other. Stack space is divided into two kinds, static allocation and dynamic allocation. Static allocations are done by the compiler, such as automatic variable (auto) allocations. Dynamic allocation is done by the Alloca function. The dynamic allocation of stacks does not need to be freed (is automatic) and there is no release function. For portable programs, the dynamic allocation of stacks is not encouraged. The allocation of heap space is always dynamic, although all data space is released back to the system at the end of the program, but accurate application memory/release memory matching is the basic element of good program.

1. Fragmentation problem: For the heap, frequent new/delete is bound to cause the memory space discontinuity, resulting in a large number of fragments, so that the program efficiency is reduced. For the stack, there is no such problem, because the stack is advanced after the queue, they are so one by one corresponding, so that there will never be a memory block from the middle of the stack pop-up, before he pops up, the last of his stack content has been ejected, detailed can > reference data structure, Here we are no longer one by one discussed.
2. Growth direction: For the heap, the growth direction is upward, that is, to the memory address increase direction; for the stack, its growth direction is downward, is toward the memory address to reduce the direction of growth.
3. Allocation method: The heap is dynamically allocated, there is no statically allocated heap. There are 2 ways to allocate the stack: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. The dynamic allocation is allocated by the Alloca function, but the dynamic allocation and heap of the stack are different, and his dynamic allocation is released by the compiler without our manual implementation.
4. Distribution efficiency: The stack is the machine system provides the data structure, the computer will be at the bottom of the stack to provide support: the allocation of special registers to store the stack address, pressure stack out of the stack have specific instructions to execute, which determines the stack of high efficiency. The heap is provided by the C + + function library, and its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will search the heap memory for the available space of sufficient size in a certain algorithm (the specific algorithm can refer to the data structure/operating system), if there is not enough space (possibly due to too much memory fragmentation), It is possible to call the system function to increase the memory space of the program data segment, so that there is a chance to get enough memory and then return. Obviously, the heap is much less efficient than the stack.

Explicitly differentiate between heap and stack:
On the BBS, heap and stack of the distinction between the problem, seems to be an eternal topic, it can be seen that beginners are often confused, so I decided to take his first surgery.
First, let's give an example:
void F ()
{
int* P=new int[5];
}
This short sentence contains the heap and stack, see new, we should first think, we allocate a heap of memory, then the pointer p. He allocates a stack of memory, so this means that a pointer to a heap of memory is stored in the stack memory. When the program determines the size of the memory allocated in the heap, then calls operator new to allocate memory, then returns the first address of the memory, put it into the stack, and his assembly code under VC6 is as follows:
00401028 Push 14h
0040102A call operator new (00401060)
0040102F Add esp,4
00401032 mov dword ptr [Ebp-8],eax
00401035 mov eax,dword ptr [ebp-8]
00401038 mov dword ptr [Ebp-4],eax
Here, we do not release the memory for simplicity, so how to release it. Is it delete p? O, wrong, should be delete []p, this is to tell the compiler: I delete an array, VC6 will be based on the appropriate cookie information to release the memory work.
Well, let's go back to our topic: What's the difference between stacks and stacks?
The main difference consists of the following points:
1. Different ways of management;
2, the space size is different;
3, can produce different fragments;
4, the growth direction is different;
5. Different ways of distribution;
6, the distribution efficiency is different;
Management mode: For the stack, is the compiler automatically managed, without our manual control; for the heap, the release of the work by the programmer control, easy to produce memory leak.
Space size: Generally in 32-bit system, heap memory can reach 4G of space, from this point of view heap memory is almost no limit. But for the stack, generally there is a certain amount of space, for example, under the VC6, the default stack space size is 1M (as if it is not clear). Of course, we can modify:
Open the project, and then operate the menu as follows: Project->setting->link, select output in category, and then set the maximum stack value and commit in the reserve.
Note: The reserve minimum value is 4byte;commit is kept in the virtual memory of the page file, it set a large stack to open up a larger value, may increase the cost of memory and startup time.
Heap and Stack, due to the use of a large number of new/delete, it is easy to create a large number of memory fragmentation, because there is no special system support, inefficient, due to the possibility of triggering a user state and nuclear mentality of switching, memory applications, the cost becomes more expensive. So the stack in the program is the most widely used, even if the function of the call also use stack to complete, function calls in the process of parameters, return address, EBP and local variables are used to store the stack. So, we recommend that you try to use stacks instead of heaps.

In addition to the comparison of the access efficiency:
Code:
Char s1[] = "AAAAAAAAAAAAAAA";
Char *s2 = "BBBBBBBBBBBBBBBBB";
The AAAAAAAAAAA is assigned at run time;
And the BBBBBBBBBBB is determined at compile time;
However, in future accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap).
Like what:
void Main ()
{
char a = 1;
Char c[] = "1234567890";
Char *p = "1234567890";
A = c[1];
A = p[1];
Return
}

The corresponding assembly code
10:a = c[1];
00401067 8A 4D F1 mov cl,byte ptr [ebp-0fh]
0040106A 4D FC mov byte ptr [ebp-4],cl
11:a = p[1];
0040106D 8B EC mov edx,dword ptr [ebp-14h]
00401070 8A mov al,byte ptr [edx+1]
00401073 FC mov-byte ptr [ebp-4],al
The first reads the elements in the string directly into the register CL, while the second reads the pointer value into the edx and reads the characters according to EdX, which is obviously slow.
Both the heap and the stack are supposed to prevent the occurrence of cross-border phenomena (unless you deliberately make them out of bounds), because the result of crossing the line is either a program crash or a heap or stack structure that destroys the program, resulting in unexpected results, even when your program is running without the above problems, you should be careful It's probably going to explode, and writing stable, secure code is the most important thing.
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.