Differences among global variables, local variables, static global variables, and static local variables in memory

Source: Internet
Author: User

Differences among global variables, local variables, static global variables, and static local variables in memory

I. program memory allocation

The memory occupied by a C/C ++ compiled program is divided into the following parts:

1. stack )-Released automatically by the compilerStores the function parameter values and local variable values. The operation method is similar to the stack in the data structure.

2. heap-generally assigned and released by the programmer. If the programmer does not release the heap, it may be recycled by the OS at the end of the program. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.

3. Global (static)-the storage of global variables and static variables is put in one area, and the initialized global variables and static variables are in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. System release after the program ends

4. Text Constant Area-constant strings are placed here. The program is released by the system.

5. program code area-stores the binary code of the function body.

Ii. Example Program

// Main. cpp

Int a = 0; global initialization Zone

Char * p1; uninitialized globally

Main ()

{

Int B; // Stack

Char s [] = "abc"; // Stack

Char * p2; // Stack

Char * p3 = "123456"; 123456 \ 0 "; // in the constant area, p3 on the stack.

Static int c = 0; // global (static) initialization Zone

P1 = (char *) malloc (10 );

P2 = (char *) malloc (20 );

// The allocated 10-byte and 20-byte areas are in the heap area.

Strcpy (p1, "123456"); // 123456 \ 0 is placed in the constant area, and the compiler may optimize it into a place with the "123456" pointed to by p3.

}

Iii. Scope:

Global variables have a global scope. Global variables can be defined in only one source file to act on all source files. Of course, other source files that do not contain the definition of a global variable must use the extern keyword to declare the global variable again.

A local variable only has a local scope. It is an automatic object (auto). It does not always exist during the program running, but only exists during the function execution. After a function call is completed, the variable is revoked, and the occupied memory is also withdrawn.

Static local variables have a local scope and are initialized only once. They exist until the first initialization ends until the program is running, the difference between global variables and global variables is that global variables are visible to all functions, while static local variables are always visible only to the defined function bodies.

Static global variables also have a global scope. The difference between static global variables and global variables is that if a program contains multiple files, it acts on the files that define it and cannot act on other files, the variable modified by the static keyword has the file scope. In this way, even if two different source files define static global variables with the same name, they are also different variables.

From the perspective of memory space allocation:
Global variables, static local variables, and static global variables are all allocated space in the static storage area, while local variables are allocated space in the stack.

From the above analysis, we can see that after a local variable is changed to a static variable, its storage mode is changed, that is, its survival time is changed. After changing a global variable to a static variable, it changes its scope and limits its scope of use. Therefore, the description of static plays different roles in different places.

4. in general:

1. different lifecycles
2. Different Functions
3. Different allocation methods

----------------------------------------------

Let's take a look at the differences between stack and stack:

1. Different allocation methods;
2. Different space sizes;
3. Different Allocation Efficiency;
4. Whether fragments can be generated is different;
5. Different Growth directions;

1. Different allocation methods

STACK:
Automatically assigned by the system. For example, declare a local variable int B in the function; the system automatically opens up space for B in the stack.
Heap:
The programmer needs to apply and specify the size. In c, the malloc Function
For example, p1 = (char *) malloc (10 );
Use the new operator in C ++
For example, p2 = (char *) new (10 );
But note that p1 and p2 are in the stack.

2. Different space sizes

Generally, in a 32-bit system, the heap memory can reach 4 GB. From this perspective, there is almost no limit on the heap memory. But for stacks, there is usually a certain amount of space. For example, under VC6, the default stack space is 1 MB.

3. Allocation Efficiency

The stack is the data structure provided by the machine system. The computer will provide support for the stack at the underlying layer: assign a special register to store the stack address, and the output stack of the Pressure Stack has a special command line, this determines the high efficiency of the stack. The heap is provided by the C/C ++ function library, and its mechanism is very complicated. For example, to allocate a piece of memory, library functions search for available space in heap memory based on certain algorithms (for specific algorithms, refer to data structures/operating systems, if there is not enough space (probably because there are too many memory fragments), 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 allocate enough memory, then return. Obviously, the heap efficiency is much lower than the stack efficiency.

4. Fragmentation issues

STACK: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.
Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application,
The linked list is traversed to find the heap node with the first space greater than the requested space. Then, the node is deleted from the idle node linked list and allocated to the program, for most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list.

For the heap, frequent new/delete operations will inevitably lead to memory space disconnections, resulting in a large number of fragments, reducing program efficiency. For the stack, this problem will not exist, because the stack is an advanced and outgoing queue. They are so one-to-one correspondence that it is impossible to have a memory block popped up from the middle of the stack, before the pop-up, the post-stack content has been popped up.

5. growth direction

For the heap, the growth direction is upward, that is, the direction for increasing the memory address; For the stack, the growth direction is downward, and the direction for decreasing the memory address.


Compared with the stack, the use of a large number of new/delete operations may easily cause a large amount of memory fragments. Due to the absence of dedicated system support, the efficiency is very low; because it may lead to switching between the user State and the core state, the memory application will become more expensive. Therefore, stacks are the most widely used in applications. Even function calls are completed using stacks. The parameters and return addresses in the function call process are as follows, both EBP and local variables are stored in stacks. Therefore, we recommend that you use stacks instead of stacks. Although the stack has so many advantages, but because it is not so flexible as the heap, sometimes it is better to allocate a large amount of memory space.

 

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.