C + + variable memory allocation and type modifiers

Source: Internet
Author: User
Tags modifiers

Objective

Understanding C + + Program memory allocations helps to understand the initialization values of variables and their lifetime. In addition, the variable type modifier also affects the initialization value of the variable and its life cycle. Mastering the initialization values of different types of variables and their lifetimes allows us to design the program with more accuracy when defining variables.


Memory allocation 1. Memory layout for C + + programs

Modern computers follow the von Neumann architecture, so the memory layout of C + + programs follows the system. It consists of 5 parts: code snippet, data segment, BSS segment, Heap and stack.

1. Code Snippets

Code Segment/text segment, often referred to as a piece of memory area used to store program execution code. The size of this area is determined before the program runs, and the memory area is usually read-only, and some schemas allow the code snippet to be writable, which allows the program to be modified. In a code snippet, it is also possible to include some read-only constant variables, such as String constants. In addition, the location of the string constant storage, also has a certain relationship with the compiler, it may also be placed in the data segment.

2. Data segment

Data segment (datasegment), usually refers to an area of memory that is used to hold the initialized global variable/static variable in the program. The data segment belongs to static memory allocation.

3. BSS segment

BSS (BSS segment), usually refers to an area of memory that is used to store uninitialized global variables/static variables in the program. BSS is the abbreviation for English block Started by symbol. BSS segments belong to static memory allocations.

4. Heap

Heap, which is used to store dynamically allocated memory segments in a process run, is not fixed and can be dynamically expanded or scaled down. When the process calls Malloc/new and other functions to allocate memory, the newly allocated memory is dynamically added to the heap (heap is expanded), and when the memory is freed with functions such as Free/delete, the freed memory is removed from the heap (heap is scaled down).

5. Stack

Stack, stack, also known as a stack, is a local variable that is temporarily created by the user store program, that is, the variables defined in the parentheses "{}" of the function (but not the static declared variables, static means that the variables are stored in the data segment). In addition, when a function is called, its arguments are also pressed into the process stack that initiates the call, and the return value of the function is stored back to the stack when the call ends. Due to the advanced post-out features of the stack, the stack is particularly handy for saving/recovering call sites. In this sense, we can think of the stack as a memory area where temporary data is stored and exchanged. Pressure stack out of the stack, and then pressed into the stack at the top of the stack, so the first stack. Also known as LIFO (LAST-IN,FIRST-OUT,LIFO).

2. Variable Memory storage

Depending on the way in which memory is applied, it is mainly divided into static storage and dynamic storage area.

1. Static Storage Area

The static storage area is already allocated when the program is compiled, and the entire running period of the program exists in this block. Static storage includes read-only storage, initialized global variables/static variable stores, and uninitialized global variables/static variable stores.

2. Dynamic Storage Area

Dynamic memory is allocated dynamically when the program is running, as needed. Dynamic storage consists primarily of heaps and stacks.

Low Address

High Address

Read-only storage area

Static Storage Area

Initialized global variable/static variable store

Uninitialized global variable/static variable store

Heap Area

Dynamic Storage Area

Stack area

int g_idx= 10; Initialized Global variables

int* G_parr; Uninitialized global variable with a default value of 0

int _tmain (int argc, _tchar* argv[])

{

NCNT storage in the stack area

int ncnt= 100;

Ppath stored on the stack, "C:\\work" is a string constant stored in the constant area

Ppath points to this string constant, so you cannot modify what Ppath points to

char* ppath= "C:\\work";

00411475 mov dword ptr [Ppath],offset string "C:\\work" (415754h)

Static variables that have been initialized

static intncurcnt = 1;

The pcnt is stored on the stack, but the memory that pcnt points to is an int assigned on the heap

char* pnewpath= New CHAR[10];

memset (Pnewpath, 0, 10);

By the upper and lower assembly code can be seen, "c:\\work" by the compiler to optimize the same constant

strcpy_s (Pnewpath, ten, "c:\\work");

004114A5 mov Esi,esp

004114A7 Push offset string "c:\\work" (415754h)

Delete[] Pnewpath;

Pnewpath = NULL;

return 0;

}

Variable type modifier 1. Const

concept : A type that is used to specify the const description of a type modifier, and the value of a constant type variable or object cannot be updated.

Grammatical form:

qualifying non-pointer types : The following two forms function, that is, variables are constants and cannot be modified.

int const MAX_DEVICE_CNT = 32;

const int min_device_cnt = 16;

Qualifying Pointer Types : Whoever is close to the limit can be understood as the nearest principle.

int nvalue = 10;

Const int* PPTR =&nvalue; Limits the value that pptr points to, but does not qualify pptr itself

int* Const PValue =&nvalue; Qualify the pvalue itself, but not the value of the pvalue pointer

Const int* Const pv= &nValue; Both pointers and values are qualified

Initialize :

I. member variables of class, initialization must be done in the constructor initialization list.

Ii. in other cases, the declaration must be defined in conjunction with the definition, i.e. the declaration.

Scope:

III. Within the function body {}, the scope is a local scope.

Iv. as a class member variable, the scope is the current class.

V. and static are declared in the class declaration, scoped globally, and accessed through the class name.

VI. Outside the class/function body, the scope is a file scope, which can only be used by the current file.

Vii. when combined with static, the scope remains the same as the file scope.

Viii. and extern combinations, the scope of this variable is changed to global.

const extern int min_device_cnt = 16; Declaration definition

extern const int min_device_cnt = 16; Declaration definition

const extern int min_device_cnt; Declaring external files when they are used

extern const int min_device_cnt; Declaring external files when they are used

Note: The current two variables have the same form of access, and the scope overlaps, and when linked, the duplicate defined error is reported. If the current constant only wants to be used within the current file, define the declaration at the front of the current CPP file. If you want to use it only in the current class, you can define it in the class declaration.

2. Static

concept: changing the life cycle of a declared variable is global.

Grammatical form: Static cannot be shared with extern, and can be arbitrarily positioned with const, type (int, and so on).

const static int min_device_cnt;

static const int min_device_cnt;

int const static MIN_DEVICE_CNT;

initialization: static stores exist for global variables/static variables, indicating that initialization values and unspecified initialization values are all possible. If the initialization value is not indicated, its default value is 0.

static int min_device_cnt = 16; Initialization value is 16

static int min_device_cnt; Uninitialized, default memory value 0

Scope:

IX. Within the function body {}, the scope is a local scope and can only be accessed for the current {}, but the lifetime is global, and the 2nd access is no longer initialized, but the last value is remembered.

X. As a class member variable, the scope is global, but must be accessed through the class name.

XI. Outside of the class/function body, the scope is a file scope, which can only be used by the current file.

Note: If 1 variables only want to be used within the current file, it is best to define them in the CPP file. If defined in the header file, then the CPP file containing the header file will generate a variable of the same name in the current file scope, not only confusing, but also wasting space.

3. extern

Concept: declares that the current variable is already defined in an external file.

syntax form: extern cannot be shared with static, and with const, type (int, etc.) can be arbitrarily positioned. The definition of Add and no extern can be, but the declaration must be added, otherwise it will cause the scope overlap link error. Additionally extern is used in combination with const, see const clause.

int max_device_cnt = 32; Declaration definitions in File A.cpp

extern int max_device_cnt = 32; Declaration definitions in File A.cpp

extern int max_device_cnt; Declaration definitions in File B.cpp

initialization: You must first have a definition, that is, you need to initialize the value before you can declare it externally.

Scope : changes the scope of the const and changes the const file scope to the global scope.

Note: An external declaration of a global array variable cannot be declared as a pointer, and must be declared as an array type. Such as:

int narr[4] ={1, 2, 3, 4}; Declaration definitions in File A.cpp

extern int narr[4]; OK: Declaration definition in File B.cpp

extern int narr[]; OK: Declaration definition in File B.cpp

4. Volatile

concept: tells the compiler that the variable that is qualified is volatile and cannot be optimized.

grammatical form:volatile in the grammatical form of basic and const, can be shared with extern, const, static. When a pointer is qualified, the pointer itself and the value pointed to by the pointer are also divided.

int* volatile VIP; VIP is avolatile pointer to int

Volatile int* IVP; IVP is a pointerto volatile int

Volatile int* volatile IVP; IVP is avolatile pointer to volatile int

initialization:The volatile limit cannot be removed, that is, when using the address, you must also limit the pointer to a value of volatile, or compile an error. The pointer takes the same address.

volatile int nvalue = 4;

int* pInt =&nvalue; Error: Cannot change the volatile property of Nvalue

Volatile int* PValue = &nvalue;//OK: Limits the value pValue points to, that is, no change nvalue

Scope : does not change scope.

Note: When do you use volatile? This needs to figure out when not to use volatile to make mistakes. Such as:

void Square (int* pValue)

{

int NA = (*pvalue);

004114FE mov eax,dword ptr [pValue]

00411501 mov ecx,dword ptr [eax]

00411503 mov dword ptr [NA],ECX

int NB = (*pvalue);

00411506 mov eax,dword ptr [pValue]

00411509 mov ecx,dword ptr [eax]

0041150B mov dword ptr [NB],ECX

}

Above this is the code that is not optimized, respectively, from the point to the memory value. In the case of optimized code, the second value may be taken directly from the register without any further value being taken from the memory. If, between two assignments, another thread changes the value pointed to by Pvalue, NB, if it still takes a value from the register, actually gets the wrong value. At this point, you need to limit the value that pvalue points to. Volatile int* pvalue are required as parameters. In this way, both the NA and NB values are true. Therefore, when multiple threads change the same variable, the variable needs to be considered for use with volatile qualifiers. Of course no volatile also does not guarantee that the current line thread multiple access to the global variable value is not changed by other threads, to achieve this effect, you need to use the critical section, mutex and other thread lock means to solve.

C + + variable memory allocation and type modifiers

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.