Local variables, global variables, heaps, stacks, static, and global "go"

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/jeffade/article/details/7958013

Preliminary knowledge-memory allocation of the program
The memory used by a program compiled by C + + is divided into the following sections

    • Stack-the compiler automatically allocates releases , stores the function's parameter values, the values of local variables, and so on. It operates in a manner similar to a stack in a data structure .
    • Heap Area -typically released by programmers, if the programmer does not release, the program may end up being recycled by the OS . Note that it is not the same as the heap in the data structure, but the distribution is similar to the linked list .
    • Global Zone (static zone)--The storage of global variables and static variables is placed in a block, initialized global variables and static variables in an area , uninitialized global variables, An uninitialized static variable is in another area adjacent to it. - System release after the program is finished
    • literal constant Area -the constant string is put here. released by the system after the program is finished
    • Program code Area - The binary code that holds the body of the function .

A normal program is usually divided into three parts: program segment, data side and Stack . in the program section is the program's machine code, read-only data, this segment is usually read-only, it is illegal to write operations . The data segment puts the static data in the program . Dynamic Data is stored through stacks .

In memory, they are in the following locations:
+------------------+ Low Memory
| Program Segment |
|------------------|
| Data Segment |
|------------------|
| Stacks |
+------------------+ Memory high end

The

Stack is a contiguous block of memory . a register (SP) called the stack pointer points to the top of the stack. At the bottom of the stack is a fixed address . A feature of the stack is the LIFO . That is, the data that is placed after the first is taken out. It supports two operations, push and pop. Push is to put data on the top of the stack, pop is the top of the stack of data out.
in high-level languages, program function calls, temporary variables in functions, are used on the stack . Why is it? Because when we call a function, we need to protect the current operation, and for the function to execute, the program can correctly find the place to continue execution, so the pass and return values of the parameters are also used in the stack. The typically references to local variables are implemented by giving them an offset to the SP . There is also a base address pointer (FP, which is BP in the Intel Chip), and many compilers actually use it to refer to local variables and parameters . Typically, the offset of the relative FP of the parameter is positive and the local variable is negative.  
When a function call occurs in a program, the computer does the following: first presses the parameter into the stack, then saves the contents of the instruction register (IP) as the return address (RET); the third one to put on the stack is the base register (FP) Then copy the current stack pointer (SP) to the FP as the new base address, and finally set aside some space for the local variable to subtract the appropriate value from the SP. &NBSP

The variables defined in the function body are usually on the stack, and the allocated memory functions such as malloc, Calloc, realloc, etc. are allocated on the heap . The defines a global amount outside of all function bodies, with the static modifier placed in the global zone (static zone) wherever it is, and the static variable defined outside the body of all functions is valid in that file and cannot be extern to another file The static representation defined in the function body is valid only in the body of the function . In addition, strings such as "ADGFDF" in the function are stored in the constant area .

Comparison:

1 Performance
stack: stack exists in RAM. The stack is dynamic, and its storage speed is the second fastest . Stack
heap: The heap is in RAM and is a common memory pool. All objects are stored in the heap . Heap

2 Request method
stack "stack":  is automatically assigned by the system .   For example, declare a local variable in the function int b; The system automatically opens up space for B in the stack  . The
heap:  requires the programmer to apply for it himself, indicating the size , in C, the malloc function such as P1 = (char *) malloc (; ) in C + + with the new operator such as P2 = ( char *) malloc (10); But note: P1, p2 itself is in the stack .

3 POST request system response
stack "Stack ": As long as the remaining space on the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow .  

heap "Heap": the first should know that the operating system has a record of the free memory address of the linked list, when the system receives the application of the program, it will traverse the list, the first space is larger than the requested space of the heap node, and then the node is removed from the list of idle nodes, and the node space allocated to the program; also, for most systems, the size of this allocation is recorded at the first address in the memory space, so that the DELETE statement in the code can properly free up the memory space. Also, because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list.

4 Application Size Limits
Stack "Stack": Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory . This sentence means that the top of the stack address and the maximum capacity of the stack is the system pre-defined , in windows, the size of the stack is 2M (and some say 1M, in short, is a compile-time determination of the constant), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small .

heap "heap": a heap is a data structure that extends to a high address, and is a discontinuous area of memory . this is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address . the size of the heap is limited by the valid virtual memory in the computer system . Thus, the space of the heap is more flexible and relatively large.

5 Comparison of application efficiency
Stack "Stack": Automatically allocated by the system, faster. But programmers can't control it .

heap "heap": is the memory allocated by new, the general speed is relatively slow, and prone to memory fragmentation, but the most convenient to use .
In addition, under Windows, the best way is to use VirtualAlloc to allocate memory, he is not in the heap, nor in the stack is directly in the process's address space to keep a fast memory, although the most inconvenient to use. But the speed is fast, also the most flexible .

6 Storage contents in stacks and stacks
stack"stack": when the function is called, the first stack is the address of the next instruction in the main function (the next executable statement of the function call statement), and then the parameters of the function, and in most C compilers, the arguments are left-to-right into the stack, Then a local variable in the function . Note that static variables are not in the stack .

When this timeafter the function call ends, the local variable is first out of the stack, then the argument, and the last stack pointer points to the first saved address, the next instruction in the main function, and the program continues to run .
heap "Heap"The size of the heap is usually stored in the head of the heap with a single byte。 In the heapspecific content with Programmer's arrangement

7 Comparison of Access efficiency
Char s1[] = "AAAAAAAAAAAAAAA";
Char *s2 = "BBBBBBBBBBBBBBBBB";
AAAAAAAAAAA is assigned at run time, while BBBBBBBBBBB is determined at compile time;ButIn subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, the heap)
Like what:
#include
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 one reads the pointer values into EDX, which is obviously slow to read the characters according to EdX.

Summary:
The difference between heap and stack can be seen in the following analogy:
Use the stack like we go to a restaurant to eat, just order (send application), pay, and eat (use), eat enough to go, do not bother to cut vegetables, wash vegetables and other preparation work and washing dishes, brush pots and other finishing work, his advantage is fast, but the freedom is small.
The use of the heap is like a DIY dish that you like to eat, more trouble, but more in line with their own tastes, and great freedom.

Local variables, global variables, heaps, stacks, static, and global "go"

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.