Memory allocation knowledge, global, local, static variables

Source: Internet
Author: User

Memory allocation knowledge, global, local, static variables

Preliminary knowledge-memory allocation for programs
The memory used by a program compiled by C + + is divided into the following sections
1, stack area (stack)-by the compiler automatically assigned to release, store the function of the parameter values, local variables and other values. The operation is similar to the stack in the data structure.
2, heap area (heap)-Generally by the programmer assigned to release, if the programmer does not release, the program at the end may be reclaimed by the OS. Note that it is different from the heap in the data structure, the distribution is similar to the list, hehe.
3, Global area (static)--------------------------------------------------------------- -System release after the program is finished
4, literal constant area-the constant string is here. Released by system after program is finished
5, program code area-the binary code that holds the function body.

A normal program is usually divided into three parts: The program segment, the data end and the stack. The program section is placed with the machine code and read-only data, which is usually read-only and is illegal for its write operations. The data segment is static data in the program. Dynamic data is stored through the stack. In memory, they are positioned as follows:
+------------------+ Low Memory
| Program Section |
|------------------|
| Data Segment |
|------------------|
| Stacks |
+------------------+ High Memory
The stack is a contiguous block in memory. A register (SP), called a stack pointer, points to the top of the stack. The bottom of the stack is a fixed address. One feature of the stack is that the LIFO first. In other words, the data that is put in is first taken out. It supports two operations, push and pop. Push is to put the data to the top of the stack, pop is the top of the stack out of the data.
In advanced languages, both program function calls and temporary variables in functions are used on the stack. Why, then? Because when we call a function, we need to protect the current operation, and in order for the function to execute, the program can correctly find the place to continue execution, so the parameter's pass and return value are also used on the stack. Typically, references to local variables are achieved by giving them an offset to the SP. There is also a base address pointer (FP, BP in the Intel chip) that many compilers actually use to refer to local variables and parameters. In general, the relative FP offset 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, the parameters are pressed into the stack, then the contents of the instruction register (IP) are saved as the return address (RET), the third is the base register (FP), and the current stack pointer (SP) is copied to the FP, as the new base address. Finally, set aside some space for local variables and subtract the appropriate values from the SP.

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.

Contrast:
1 performance
Stack: Stacks exist in RAM. The stack is dynamic, and its storage speed is the second fastest. Stack
Heap: The heap is in RAM and is a general-purpose memory pool. All objects are stored in the heap. Heap

2 Application methods
Stack: Automatically allocated by the system. For example, declare a local variable int b in a function; The system automatically opens up space for B in the stack
Heap: Programmers are required to apply themselves and indicate size, in C malloc functions such as P1 = (char *) malloc (10);
In C + +, use the new operator such as P2 = (char *) malloc (10); But note that P1, p2 itself is in the stack.

3 response of the system after application
Stack: As long as the remaining space of the stack is larger than the application space, the system will provide memory for the program, otherwise it will be reported abnormal stack overflow.
Heap: First you should know that the operating system has a record of the free memory address of the list, when the system received the application of the program,
Will traverse the list to find the first heap node that is larger than the requested space, the node is then removed from the list of free nodes, and the space of the node is allocated to the program, and for most systems, the size of this assignment is recorded at the first address in the memory space, so that The DELETE statement in your code can properly free this memory space. In addition, because the size of the found heap node does not necessarily equal the size of the application, the system automatically puts the extra part back into the free list.

4 Limit of application size
Stacks: In Windows, stacks are data structures that extend to a low address and are a contiguous area of memory. The address of the top of the stack and the maximum capacity of the stack are predetermined by the system, in Windows, the size of the stack is 2M (also some say 1M, in short, a compile-time constant), if the application space over the stack of remaining space, will prompt overflow. Therefore, the space can be obtained from the stack is small.
Heap: The heap is a data structure that is extended to a high address and is a contiguous area of memory. This is because the system is used to store the free memory address of the list, nature is discontinuous, and the link list of the traversal direction is from the low address to the high address. The size of the heap is limited by the virtual memory available in the computer system. This shows that the heap to obtain a more flexible space, but also relatively large.

5 Comparison of the application efficiency
The stack is automatically allocated by the system, faster. But programmers are out of control.
A heap is a memory that is allocated by new, typically slower, and prone to memory fragmentation, but is most convenient to use.
In addition, in Windows, the best way is to allocate memory with VirtualAlloc, he is not in the heap, nor in the stack is directly in the process of the address space to keep a fast memory, although the most inconvenient to use. But fast, and most flexible.

6 stacks and stacks of stored content
Stacks: When a 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). Then there are the parameters of the function, in most C compilers, the parameters are pushed from right to left, and then the local variables in the function. Note that static variables are not in the stack.
When the function call is finished, the local variable first goes out of the stack, then the argument, and the last stack pointer points to the address that was first saved, the next instruction in the main function, where the program continues to run.
Heap: The size of the heap is usually stored in a byte at the head of the heap. The specifics of the heap are arranged by the programmer.

7 Comparison of Access efficiency
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:
#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 reads the pointer value into the edx and reads the characters according to EdX, which is obviously slow.

Summary:
The difference between stacks and stacks can be seen in the following analogy:
Use stacks just like we eat in restaurants, just order (apply), pay, and eat (use), go after full, do not have to pay attention to cutting vegetables, vegetables, such as preparation and washing dishes, such as cleaning the pot, his advantage is fast, but the degree of freedom is small.
The use of the heap is like a do-it-yourself like to eat dishes, more trouble, but more in line with their own taste, and greater freedom.

Global variables, static data, constants are stored in the global data area, the code for all functions is stored in the code area, and local variables, function parameters, return data, and return addresses, which are allocated for running functions, are stored in the stack area.   &NBSP
So in the same process, both global and static variables for multiple tasks (threads) should share the same block of memory (global data area)   &NBSP,
and reload the code in different processes. Global and static variables between processes do not, of course, have the same piece of memory.   &NBSP
under PSOs, each task is a different thread, so the global and static variables for each task are in the same memory. And my other program (in SCO Unix) is that every run is a new process, so the global and static variables for each process have different memory

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.