Static global variables and ordinary global variables

Source: Internet
Author: User
Tags stack pop

Memory allocation of a program

The memory consumed 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, and the distribution is similar to the linked list.

3, Global zone (static area) (static)-the storage of global variables and static variables is placed in a piece, the initialization of global and static variables in a region, uninitialized global variables and uninitialized static variables in another adjacent area. System released after program is finished

4, literal constant area-the constant string is here. The system is released after the program is finished.

5, program code area-the binary code that holds the function body.

Second, the example procedure

Main.cpp

int a = 0; Global initialization Area

Char *p1; Global uninitialized Zone

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 area

P1 = (char *) malloc (10);

P2 = (char *) malloc (20);

Areas that are allocated 10 and 20 bytes are in the heap area.

strcpy (P1, "123456"); 123456\0 is placed in a constant area, and the compiler may optimize it with the "123456" that the P3 points to as a place.

}

Three, from the scope of view:

Global variables have global scope. Global variables can be used for all source files only if they are defined 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.

A local variable is also only a local scope, which is an automatic object (auto) that does not always exist during the run of the program, but only exists during the execution of a function, the variable is revoked, and the memory occupied by the function is retracted.

A static local variable has a local scope, it is initialized only once, and since the first time it is initialized until the end of the program, it differs from the global variable in that the global variable is visible to all functions, while the static local variable is always visible only to the function body that defines itself.

Static global variables also have global scope, which differs from global variables in that if a program contains more than one file, it acts on the file in which it is defined and does not function in other files, that is, a variable modified by the static keyword has a file scope. This way, even if two different source files have defined static global variables of the same name, they are also different variables.

From the allocated memory space:
Global variables, static local variables, static global variables are allocated space in the static storage area, and local variables in the stack allocated space.

From the above analysis, we can see that the change of the local variable to the static variable is the change of its storage mode that changes its lifetime. Changing the global variable to a static variable changes its scope and limits its use. So the static this specifier plays a different role in different places.

Four, in general, is:

1. Different life cycle
2, the scope of action is different
3. Different distribution mode

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

Let's look at the difference between the heap and the stack:

1. Different ways of distribution;
2, the space size is different;
3, the distribution efficiency is different;
4, can produce different fragments;
5, the growth direction is different;

1. Different distribution mode

Stack:
Automatically assigned 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:
Requires programmers to apply themselves, and indicate size, in C malloc function
such as P1 = (char *) malloc (10);
Using the new operator in C + +
such as P2 = (char *) new (10);
But note that P1, p2 itself is in the stack.

2. Different space size

In general, under the 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.

3. Distribution efficiency

Stack is the machine system provides the data structure, the computer will support the stack at the bottom: 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.

4. Fragmentation issues

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.

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, this problem will not exist, because the stack is the advanced 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, on top of his last stack content has been ejected.

5. Growth direction

For the heap, the growth direction is upward, that is, the direction of the increase to the memory address, for the stack, it is the direction of growth is downward, the memory address to reduce the direction of growth.


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. Although the stacks have so many benefits, they are not as flexible as the heap, and sometimes allocate a lot of memory space, or use a heap better.


What is the difference between a static function and a normal function? functions that are modified by static are defined in the source code file and cannot be invoked by code files other than the source code file. The normal function, by default, is extern, that is, the function can be called by other code files.
The function is defined as a static function by adding the keyword static before the return type of the function. The definition and declaration of a common function are extern by default, but a static function is only visible in declaring his file and cannot be used by other files. Therefore, defining static functions has the following benefits:
<1> other files can define functions with the same name, and no conflict occurs.
<2> static functions cannot be used by other files.


What is the difference between a static global variable and a normal global variable. What is the difference between a static local variable and a normal local variable.   What is the difference between a static function and a normal function.
A:
1) a global variable (external variable) is preceded by a description of static to form a statically global variable. The global variable itself is the static storage mode, static global variables are of course also static storage mode. The two are not different in the way they are stored. The difference between the two is that the scope of the Non-static global variable is the entire source program, and 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, that is, it is only valid within the source file that defines the variable, and it 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 only be common to functions within that source file, so it is possible to avoid causing errors in other source files.
2) from the above analysis, we can see that changing the local variable to a static variable is changing its storage mode that changes its lifetime.  Changing the global variable to a static variable changes its scope and limits its use. &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP,
3) The static function differs from the normal function scope, only in this file. Functions that are used only in the current source file should be described as internal functions (static), and internal functions should be described and defined in the current source file. For functions that can be used outside the current source file, you should indicate in a header file that the source file that you want to use these functions to include the header file
to sum up:
What is the difference between a static global variable and a normal global variable:
Static global variable is only first made once,   Prevent being referenced in other file units;
What is the difference between a static local variable and a normal local variable:
A static local variable is initialized only once, the next time based on the last result value, and the
static function differs from a normal function:
The static function is only one copy in memory, Normal functions maintain a copy of each invocation

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.