Original: http://blog.csdn.net/tigerjibo/article/details/7423728
Differences in heap and stack in C language
I. Preface:
C Language program compiled after the formation of a compiled, connected to form a binary image file by the stack, heap, data segment (composed of three parts: read-only data segment, has initialized the read and write data segments, uninitialized data segment, BBS) and code snippets, as shown in:
1. Stack: The compiler automatically allocates releases, stores the function's parameter values, and local variables are equivalent. It operates in a manner similar to a stack in a data structure.
2. Heap area: Typically released by programmers, if the programmer does not release it, it may cause a memory leak. The heap is different from the stack in the data structure, and its class is linked to the list.
3. Program code area: the binary code that holds the function body.
4. Data segment: Consists of three parts:
1> read-only data segment:
Read-only data segments are data that the program uses that are not changed, and use this data in a way that looks like a table-type operation, because these variables do not need to be changed, so they only need to be placed in read-only memory. Variables that are typically const-modified and literal constants used in programs are typically stored in read-only data segments.
2> initialized read-write data segment:
Initialized data is declared in the program, and has the initial value of the variable, these variables need to occupy memory space, when the program executes, they need to be in a writable memory area, and have an initial value for the program to read and write. In a program, it is generally a global variable that has already been initialized, a static local variable that has already been initialized (the initialized variable of the static modifier)
3> uninitialized Segment (BSS):
Uninitialized data is declared in the program, but there are no initialized variables that do not need to occupy memory space before the program runs. Similar to the read-write data segment, it also belongs to the static data area. However, the data in this paragraph is not initialized. Uninitialized data segments are generated only during the initialization phase of the run, so its size does not affect the size of the destination file. In a program, there are generally no initialized global variables and static local variables that are not initialized.
Two. Heap and Stack differences
1. How to Apply
(1) stack (SATCK): Automatically assigned by the system. For example, declare a local variable int b in the function, and the system automatically opens up space for B in the stack.
(2) Heap: Requires the programmer to apply (call Malloc,realloc,calloc), and specify the size, and released by the programmer. Easy to produce memory leak.
Eg:char p;
p = (char *) malloc (sizeof (char));
However, p itself is in the stack.
2. Restrictions on size of applications
(1) Stack: The stack in Windows is the data structure that extends to the bottom address, which is a contiguous area of memory (it grows in the opposite direction as the memory is growing). The size of the stack is fixed. If the requested space exceeds the remaining space on the stack, overflow will be prompted.
(2) Heap: A heap is a data structure with a high address extension (it grows in the same direction as the memory) and is a discontinuous area of memory. This is due to the fact that the system uses a linked list to store the free memory address, which is naturally discontinuous, while the traversal direction of the list is from the bottom address to the high address. The size of the heap is limited by the valid virtual memory in the computer system.
3. System response:
(1) Stack: As long as the stack of space is larger than the application space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.
(2) Heap: First of all should know that the operating system has a record of the free memory address of the list, but the system receives the application of the program, will traverse the list, the first space is larger than the requested space of the heap node, and then delete the node from the free list, and the node's space allocated to the program, in addition, The size of this allocation is recorded at the first address in this memory space, so that the free statement in the code can properly release the memory space. In addition, the size of the found heap node is not necessarily exactly equal to the size of the request, and the system automatically re-places the extra portion into the idle list.
Note: For the heap, for the heap, the frequent new/delete will inevitably 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 problem.
4. Application efficiency
(1) The stack is automatically assigned by the system and is fast. But programmers can't control it.
(2) Heap is the memory allocated by malloc, the general speed is relatively slow, and easy to produce fragments, but the most convenient to use.
5. Storage content in heaps and stacks
(1) Stack: When a function is called, the address of the next statement in the main function of the first stack, followed by the parameters of the function, the arguments are in the stack from right to left, and then the local variables in the function. Note: Static variables are not in the stack.
When the function call is finished, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues execution from that point.
(2) Heap: The size of the heap is usually stored in a heap with a byte in the head.
6. Access efficiency
(1) Heap: char *s1= "Hellow Tigerjibo";
(2) Stack: char s1[]= "Hellow Tigerjibo"; is assigned at run time; it is faster to use an array than a pointer, and the pointer needs to be brokered in the underlying assembly with the EDX register, and the array is read on the stack.
Add:
The stack is the data structure provided by the machine system, the computer will support the stack at the bottom: allocate the address of the special register storage stack, the stack stack has special instruction execution, which determines the efficiency of the stack is high. The heap is provided by C + + function library, its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will follow a certain algorithm (the specific algorithm can refer to the data structure/operating system) in the heap memory to search for available enough space, if there is not enough space (possibly due to too much memory fragmentation), It is possible to invoke the system function to increase the memory space of the program data segment, so that there is a chance to divide the memory in sufficient size and then return. Obviously, the heap is much less efficient than the stack.
7. Allocation Method:
(1) The heap is dynamically allocated and there is no statically allocated heap.
(2) There are two ways to allocate stacks: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. Dynamic allocations are allocated by the ALLOCA function, but the dynamic allocation of stacks is different from the heap. Its dynamic allocation is released by the compiler without the need for manual implementation.
The 1.c++ variable has different scopes according to the different life cycles of the defined positions, and the scope can be divided into 6 types:
Global scopes, local scopes, statement scopes, class scopes, namespace scopes, and file scopes.
From the scope view:
1> Global variables have global scope. A global variable can be used for all source files simply by defining it in one source file. Of course, other source files that do not contain global variable definitions need to declare the global variable again with the extern keyword.
2> static local variable has a local scope, it is initialized only once, since the first time it was initialized until the end of the program runs, it differs from the global variable is that the global variable is visible to all functions, while static local variables are always visible to the body of the function that defines itself.
3> Local variables are also only local scope, it is an automatic object (auto), it does not persist during the program run, but only during the execution of the function, the function of the execution of a call after the end of the variable is revoked, the memory occupied by the recovery.
4> Static global variables also have global scope, which differs from global variables in that if a program contains multiple files, it acts on the file that defines it and does not work in other files, that is, variables modified by the static keyword have a file scope. This way, even if two different source files define static global variables of the same name, they are also different variables.
2. From allocating memory space, see:
1> global variables, static local variables, static global variables allocate space in static storage, and local variables allocate space in stacks
The 2> global variable itself is static storage, and static global variables are, of course, static storage methods. The two are not different in how they are stored. The difference between the two is that the scope of the non-static global variable is the whole source program, when a source program consists of multiple source files, non-static global variables are valid in each source file. A static global variable restricts its scope, which is valid only within the source file that defines the variable, and cannot be used in other source files of the same source program. Because the scope of a static global variable is limited to one source file, it can be common only for functions within that source file, so you avoid causing errors in other source files.
1) Static variables are placed in the program's static data store (globally visible) so that the original assignment can be maintained at the next call. This is the difference between a stack variable and a heap variable.
2) variables are used to tell the compiler that they are only visible within the scope of the variable. This is the difference between it and the global variable.
From the above analysis, it can be seen that changing the local variable to a static variable changes its storage mode, which changes its life time. Changing a global variable to a static variable changes its scope and limits its scope of use. So the function of the static descriptor is different in different places. Should be taken into consideration.
Tips:
A. If the global variable is accessed only in a single C file, you can modify the variable to a static global variable to reduce the coupling between the modules;
B. If the global variable is accessed only by a single function, the variable can be changed to a static local variable of the function to reduce the coupling between the modules;
C. When designing and using functions that access dynamic global variables, static global variables, and static local variables, you need to consider the reentrant problem, because they are all placed in a static data store and are globally visible;
D. If we need a reentrant function, then we must avoid using the static variable in the function (a function called "Internal memory" function)
The static variable condition must be used in the function: for example, when the return value of a function is a pointer type, it must be the address of the static local variable as the return value, and if it is the auto type, it is returned as the wrong pointer.
Differences in heap and stack in C language