How to layout the memory of C Programming programs
In C, each variable and function has two attributes:Data Type
AndData storage category
.
Storage Class of local variables and global variables in C Language (static
,extern
,auto
,register
)
1. Partition variables from the scope of variables (that is, from
Space
).
Lifetime
).
Store the following data:
Code segment (text)
,Read-only data segment (rodata)
,Read/write data segments (rwdata)
,Uninitialized data segment (bbs)
The static storage area stores all global variables. These variables will be generated after the link, and will be released after the program is executed. During the program execution process, they occupy a fixed storage unit, instead of dynamically allocating and releasing
2.2. Dynamic Storage Zone
Store the following data:
Function Parameters
,Automatic variable (local variable without static Declaration)
,Field Protection and return address during function call
For the above data, dynamic storage space is allocated when the function starts calling, and the space is released when the function ends.
3. the user memory space is divided into three parts: 1. Program Zone
Machine code waiting for execution in one row
2. static storage area 3. Dynamic Storage Area 4. From C program
Runtime
It can also be divided into the following storage area 1. Code segment (Code | Text)
A code segment consists of the machine code executed in the program. In C, program statements are compiled to form machine code. During program execution, the CPU program counter points to eachMachine code
And run by the processor in sequence.
2. Introduction to read-only data segments (ROData) 2.1 ROData
Read-only data segments are data that will not be changed by the program. They are used in a similar way as table-based operations. Because these variables do not need to be changed, therefore, you only need to place it in read-only memory. The read-only data segment is generated by the data used in the program. This data segment does not need to be changed during running. Therefore, the compiler puts this data segment into the read-only part. C Language
Read-Only global variables
,
Read-Only local variables
, Used in the program
Constant
Meeting
During Compilation
Quilt
Put
To
Read-only data Zone
.
Note:
: Define the global variable const char a [100] = {"ABCDEFG"}. a read-only data zone with a size of 100 bytes will be generated and initialized using "ABCDEFG. If it is defined as const char a [] = {"ABCDEFG"}, 8 bytes of read-only data segment (and '\ 0') are generated based on the string length '),
Therefore, full initialization is generally required in read-only data segments.
2.2 Example
# Define A = 18; ## constant const int A = 18; ## read-only global variable int main () {const int B = 18; ## read-only local variable}
3. Read and Write data segments initialized (RW data) 3.1 RWData Introduction
Initialized data is declared in the program and has initial values. These variables need to occupy the storage space. During program execution, they need to be located in the read/write memory area, and has an initial value for reading and writing when the program is running. All global variables are stored in the static storage area,
Assign a storage area to the global variable when the program starts execution.
,
Release after the program line is completed
. In
They occupy fixed storage units during Program Execution
,
Instead of dynamically allocating and releasing
;
Global Variables
Static local variables
3.2 Example
Int global_init_val = 1; ## global variable int main (int argc, char * argv []) {static int a = 1; ## static (static) local variable}
4. uninitialized data segment (BSS) 4.1 BSS Introduction
Uninitialized data is declared in the program, but there are no initialized variables. These variables do not need to occupy storage space before the program runs.
4.1 Example
Int global_noinit_val; ## global uninitialized global variable char * p1; ## global uninitialized global variable int main (int argc, char * argv []) {......}
5. Introduction to heap 5.1 heap Space
Heap memoryOnly appears when the program is running
, Generally by programmersAllocate
AndRelease
.
If you have an operating systemProgram not released
,Operating System
May be inProgram
(For exampleProcess
)Reclaim memory after completion
.
5.2 Example
P1 = (char *) malloc (10); # The allocated 10 and 20 bytes are in the heap p2 = (char *) malloc (20 );
6. Introduction to stack (stack) 6.1 stack space
Stack memory
Only appears when the program is running
, In
Variables used inside the Function
,
Function Parameters
And
Return Value
Set
Stack usage
The stack space is automatically allocated and released by the compiler.
Stack space
Yes
Dynamic Development
And
Reclaim
. During function calling, if
There are many levels of function calls
, The required
The stack space is gradually increasing.
For
Parameter transfer
And
Return Value
If you use
Large struct
, In
The stack space used will also be relatively large.
.
The 6.2 stack zone is mainly used to store the following data. The return value of the Parameter Function of the dynamic variable function within the function is 6.3 Example.
Void main (void) {int B ;## stack char s [] = "abc" ;## stack char * p2 ;## stack char * p3 = "123456 "; #123456 \ 0 in the constant zone # p3 on the stack .}
============================================================ Gorgeous split line ==== ======================================
5. Storage classes of four types of local variables and global variables (
static
,
extern
,
auto
,
register
) 5.1 Static
Sometimes you want the local variable value in the function to keep the original value without disappearing after the function call. In this case, you should specify the local variable as "static local variable" and declare it with the keyword "static.
int f(int a){ auto int b=0; static int c=3; b=b+1; c=c+1; return(a+b+c);}int main(void){ int a=2,i; for(i=0;i<3;i++) printf("%d",f(a));}
Description of static local variables:
1) Static local variables belong to the static storage class and are allocated to storage units in the static storage area. The program is not released during the entire running period. Automatic variables (that is, dynamic local variables) belong to the dynamic storage class, occupying the dynamic storage space, and are released after the function call ends.
2) assign an initial value to a static local variable during compilation, that is, assign the initial value only once. Assign the initial value to an automatic variable when the function is called, and re-assign the initial value to each callback function, it is equivalent to executing a value assignment statement.
3) if initial values are not assigned when defining local variables, the initial values 0 (For numeric variables) or null characters (for character variables) are automatically assigned to static local variables during compilation ). For automatic variables, if the initial value is not assigned, its value is an uncertain value.
5.2 Extern
External variables
(Global Variables
Is defined outside the function, its scope is from the definition of the variable, to the end of the program file. If the external variable is not defined at the beginning of the file, its effective scope is limited to the end of the file at the definition. If the function before defining a vertex wants to reference this external variable, you should use the keyword before referencingextern
For this variable,External variable Declaration
".Indicates that the variable is an external variable that has been defined.
. With this statement, you canStatement
Starting from,Use this external variable legally
.
int max(int x,int y){ int z; z=x>y?x:y; return(z);}int main(void){ extern A,B; printf("%d\n",max(A,B));}int A=13,B=-8;
Note:
In the last line of the program file, the external variables A and B are defined. However, since the external variables are defined after the main function, external variables A cannot be referenced in the main function, b. Now, we use extern in the main function to declare the external variables A and B, and then we can legally use the external variables A and B from the Declaration.
5.3 Auto
If the local variables in the function are not specifically declared as static storage classes, they are dynamically allocated storage space, and the data is stored in the dynamic storage area.
. The form parameters in the function and the variables defined in the function (including the variables defined in the composite statement) belong to this class. When the function is called, the system will allocate storage space to them, these buckets are automatically released at the end of the function call. This type of local variable is calledAutomatic Variable
. Auto variables use the keyword auto for the storage class declaration.
Int f (int a)/* defines the f function. a is the */{auto int B, c = 3;/* defines the B and c automatic variables */}
A is the form parameter, B, c is the automatic variable, and the initial value of c is 3. After the f function is executed, the storage units a, B, and c are automatically released.
The keyword auto can be omitted,If auto is not written, it is implicitly set to "Automatic Storage category", which is a dynamic storage method.
. OccupiedStack space
5.4 Register
To improve efficiency, the C language allows you to place the value of a local variable in a register in the CPU. This variable is called a "register variable" and is declared using the keyword register.
int fac(int n){ register int i,f=1; for(i=1;i<=n;i++) f=f*I; return(f);}int main(void){ int i; for(i=0;i<=5;i++) printf("%d!=%d\n",i,fac(i));}
Note:
1)Only Local Automatic variables and formal parameters can be used as register variables
;
2) The number of registers in a computer system is limited,Multiple register variables cannot be defined.
;
3)Local static variables cannot be defined as register variables.
.
6. Summarize from the scope of the variable (that is, from
Space
).
Minute
, Can be divided
Global Variables
And
Local variable
. From the time when the variable value exists (that is
Lifetime
).
Minute
, Can be divided
Static storage
Method and
Dynamic Storage
Method.
Code segment
,Read-only data segment
,Read/write data segment
,Uninitialized data segment
BelongStatic Zone
Static Zone
: A fixed storage space is allocated during the running of the program.
Heap
AndStack
BelongDynamic Region
Dynamic Region
: Dynamically allocates storage space as needed during the running of the program.
Code segment
,Read-only data segment
AndRead/write data segment
SetGenerated after the link
Uninitialized data segment
Set
Open up during program Initialization
While
Heap
And
Stack
Set
Allocate and release programs during running
. C language programs are divided
Image
And
Runtime
Two statuses.
In the compiled-connected Image
, Will only contain
Code segment (Text)
,
Read-only Data segment (RO Data)
And
Read/write Data segments (RW Data)
. In
Before running the program
To dynamically generate uninitialized data segments (
BSS
) In
Program Runtime
Will also be dynamically formed
Heap)
Region and
Stack)
Region. In general, in a static image file, each part is called
Section)
And each part in the runtime is called
Segment (Segment)
. If not detailed, it can be collectively referred to
Segment
. C language in
After compilation and Connection
, Will generate
Code segment
(Text), read-only data segment (
RO Data
) And read/write data segments (
RW Data
). In
Runtime
In addition to the preceding three regions, including uninitialized data segments (
BSS
) Region and heap (
Heap
) Region and stack (
Stack
. 7. Some Instances
Const char ro [] = {"this is read only data"}; // read-only data zone static char rw_1 [] = {"this is global read write data "}; // initialized read/write data segment char BSS_1 [100]; // uninitialized data segment const char * ptrconst = "constant data"; // put the string in the read-only data segment int main () {short B; // occupies 2 bytes of char a [100] on the stack; // 100 bytes are opened on the stack, its value is its first address char s [] = "abcdefg"; // s occupies 4 bytes on the stack, and "abcdefg" is placed in the read-only data storage area, occupies 8 bytes of char * p1; // p1 occupies 4 bytes of char * p2 = "123456"; // p2 occupies the stack, the content pointed to by p2 cannot be changed. "123456" is in the read-only data zone static char rw_2 [] = {"this is local read write data "}; // static char BSS_2 [100]; // static int c = 0; // global (static) initialization zone p1 = (char *) malloc (10 * sizeof (char); // allocate the memory area in the heap zone strcpy (p1, "xxxx"); // put "XXXX" in the read-only data zone, 5 bytes free (p1); // use free to release the memory indicated by p1 return 0 ;}
The read/write data segment contains the initialized global variable static char rw_1 [] and the local static variable static rw_2 []. the difference is whether the functions are used inside the function or can be used in the entire file during coding. Rw_1 [] will be placed in the read/write data zone regardless of whether there is static modification, but whether it can be referenced by other files or not. The latter is different. It is a local static variable placed in the read and write data area. If there is no static modification, its meaning changes completely, it will be a local variable opened up in the stack space, rather than a static variable. Here rw_1 [], rw_2 [] does not have a specific value, indicating that the size of the static zone is determined by the length of the subsequent strings.
For uninitialized data areas BSS_1 [100] And BSS_2 [100], the difference is that the former is a global variable and can be used in all files; the latter is a local variable, it is used only within the function. The value after Initialization is not set for the uninitialized data segment. Therefore, the value must be used to specify the size of the region. The editor sets the length to be increased in BSS based on the size.