How to layout the memory of C programming program

Source: Internet
Author: User

In the C language, each variable and function has two properties: 数据类型 and 数据的存储类别 .
Storage categories for local variables and global variable variables in C language ( static ,,, extern auto register )

1. Divide the variable from the scope of the variable (that is, from 空间) angle to 1. Global Variables 2. Local Variables 2. The time or storage class from which the variable value exists (that is, 生存期) angle to 2.1. Static Storage Area

存放下面数据:代码段(text), 仅仅读数据段(rodata) , 读写数据段(rwdata) ,未初始化数据段(bbs)

The static store holds all the global variables, which are generated after the link, the execution of the program is released, and the program executes the fixed storage unit while it is not dynamically allocated and freed.

2.2. Dynamic Storage Area

存放下面数据:函数形參, 自己主动变量(未加static声明的局部变量) ,函数调用时的现场保护和返回地址

For these data, the dynamic storage space is allocated when the function starts calling. Frees the space at the end of the function.

3. From the user memory space angle is divided into three parts 1. Program Area
2. Static Storage area 3. Dynamic Storage 4. From the C program 执行时can also be divided into the following storage area 1. Snippet (Code | Text)

The code snippet consists of the machine code executed in the program.

In the C language. After the program statement is compiled, the machine code is formed. During the execution of the program, the CPU's program counter points to each piece of code snippet 机器代码 . and is executed sequentially by the processor.

2. Read-only data segment (RODATA) 2.1 Rodata Introduction
  1. Read-only data segments are data that the program uses that are not changed, and the way in which the data is used is similar to a table-type operation. Because these variables do not need to be changed, they simply need to be placed in read-only memory.
  2. A read-only segment is generated by the data used in the program, which is characterized by the fact that it does not have to be changed in execution, so the compiler places the data segment into a read-only section. In C language 仅仅读全局变量 , 仅仅读局部变量 . will be used in the program 常量 在编译时 放入 仅仅读数据区 .
  3. 注意: Defines the global variable const char a[100]={"ABCDEFG"}, generates a read-only data area of size of 100 bytes, and initializes it with "ABCDEFG".

    The assumption is defined as: const char a[]={"ABCDEFG"}; generates 8 bytes of read-only data (and '% ') based on the length of the string.所以在仅仅读数据段中,一般都须要做全然的初始化。

2.2 Example
#define A=18;       ##常量constint18;     ##仅仅读全局变量int main(){    constint18;     ##仅仅读局部变量}
3. Initialized read-write data segment (RW data) 3.1 Rwdata Introduction


  1. Initialized data is a variable that is declared in a program and has an initial value. These variables need to occupy memory space. They need to be in a writable memory area while the program is executing. and has the initial value. Read and write when the program executes.
  2. Global variables are all stored in the static storage area 在程序開始执行时给全局变量分配存储区 . 程序行完成就释放. In 程序执行过程中它们占领固定的存储单元 , 而不动态地进行分配和释放 ;

Global variables
Static local Variables

3.2 Example
int global_init_val=1;                   ## 全局变量int main(intchar * argv[]){    staticint a=1;                      ## 静态(static) 局部变量}
4. Uninitialized data segment (BSS) 4.1 BSS Introduction

Uninitialized data is declared in the program, but there are no initialized variables that do not need to occupy memory space before the program executes.

4.1 Example
int global_noinit_val;                   ## 全局未初始化全局变量char *p1;                                ## 全局未初始化全局变量int main(intchar * argv[]){    ......                      }
5. Heap 5.1 Heap Space Introduction

Heap Memory 仅仅在程序执行时出现 . Generally by the program ape 分配 and 释放 .


In the case of an operating system, it is assumed 程序没有释放 that it 操作系统 may be in 程序 (for example, one 进程 ) 结束后回收内存 .

5.2 Example
p1 = (charmalloc(10);     ## 分配得来的10和20个字节的区域就在堆区p2 = (charmalloc(20);
6. Stacks (stack) 6.1 Stack space Introduction
  1. Stack memory 仅仅在程序执行时出现 . In 函数内部使用的变量 , 函数的參数 as well as 返回值 the 使用栈 space,
  2. The stack space is actively allocated and freed by the compiler itself.

  3. 栈空间is 动态开辟 with 回收 the. In the process of function invocation, it is assumed 函数调用的层次比較多 that the required栈空间也逐渐加大
  4. For 參数的传递 and 返回值 , suppose 较大的结构体 to use, in 使用的栈空间也会比較大 .
The 6.2 stack area is primarily used for storage of the following data
    1. Dynamic variables inside a function
    2. The parameters of the function
    3. return value of the function
6.3 Example
void main(void){  int b;                    ## 栈  char"abc";         ## 栈  char *p2;                 ## 栈  char"123456";      ## 123456\0在常量区  ## p3 在栈上。}


=================================== Gorgeous cutting line =========================

5. Storage categories for 4 local variables and global variables ( static, extern, auto, register) 5.1 Static

Sometimes you want the value of a local variable in a function to remain the original value after the function call ends, and you should specify the local variable as a static local variable and declare it with the keyword static.

int f(int a){    autoint b=0;    staticint 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));}

对静态局部变量的说明:

1) Static local variables are static storage classes that allocate storage units within a static storage area. is not released during the entire execution of the program. The active variable (i.e. dynamic local variable) belongs to the dynamic storage category. Represents the dynamic storage space, which is released when the function call ends.
2) Static local variables are assigned the initial value at compile time, that is, the initial value is assigned only once, while the initial value of the active variable is performed at the function call, and once again the initial value is given once for each function call. Equivalent to executing an assignment statement.
3) Assuming that the local variable is not assigned the initial value, then for the static local variable, the compiler will voluntarily assign the initial value of 0 (for numeric variables) or null characters (to the character variable). For the self-active variable, assuming that the initial value is not assigned, it is an indeterminate value.

5.2 Extern

外部变量( 即全局变量 ) is defined outside of the function. It is scoped to start at the definition of the variable and at the end of the program file. Suppose an external variable is not defined at the beginning of the file, and its valid scope is limited to the definition to the end of the file. Assuming that the function before the definition point wants to refer to the external variable, the variable should be "" with the keyword before the reference extern 外部变量声明 .

表示该变量是一个已经定义的外部变量。 With this statement. will be able to start from " 声明 ." 合法地使用该外部变量.

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;

说明:

An external variable A is defined in the last 1 lines of this program file. B, but since the position defined by the external variable is after the function main, the external variable, a, B, cannot be referenced in the main function. Now we use extern for A and B "external variable declarations" in the main function to be able to legitimately work with the external variables A and b from the declaration.

5.3 Auto

函数中的局部变量。如不专门声明为static存储类别,都是动态地分配存储空间的。数据存储在动态存储区中

The formal participation in the function and the variables defined in the function (including the variables defined in the compound statement) belong to this class, and the system allocates storage space to the function when it is called, and voluntarily frees the storage space at the end of the function call. This type of local variable is called 自己主动变量 . Own the active variable with the keyword auto as the storage class declaration.

int f(int a)         /*定义f函数,a为參数*/{    autoint b,c=3;     /*定义b,c自己主动变量*/}

A is the shape of the participation, B,C is the active variable, the initial value of C 3. After executing the F function, you voluntarily release a. The storage unit that the B,c occupies.
The keyword auto can be omitted auto不写则隐含定为“自己主动存储类别”,属于动态存储方式 .

Occupied栈空间

5.4 Register

For efficiency, the C language agrees to place the value of a local variable in a register in the CPU, which is called a "register variable" and is declared with the keyword register.

int fac(int n){    registerint 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));}

说明:

1) 仅仅有局部自己主动变量和形式參数能够作为寄存器变量 .
2) The number of registers in a computer system is limited 不能定义随意多个寄存器变量 .
3) 局部静态变量不能定义为寄存器变量 .

6. Summary
  1. From the scope of the variable (that 空间 is, from) the angle , can be divided into 全局变量 and 局部变量 .
  2. From the time of the existence of the variable 生存期 value (that is) angle , can be divided into 静态存储 ways and 动态存储 means.
  3. 代码段, 仅仅读数据段 , 读写数据段 , 未初始化数据段 belong to静态区域

    静态区域: means the allocation of a fixed amount of storage space during program execution

  4. and belonging to动态区域

    动态区域: Is the way in which storage space is allocated dynamically during program execution, depending on the need.

  5. 代码段, 仅仅读数据段 and 读写数据段 will在链接之后产生

  6. 未初始化数据段Will在程序初始化的时候开辟
  7. and and will 在程序的执行中分配和释放 .
  8. The C language program is divided into 映像 执行时 two different states.

    在编译-连接后形成的映像中, will only include 代码段(Text) , 仅仅读数据段(RO Data) and 读写数据段(RW Data) .

  9. In the 程序执行之前 . Dynamic generation of uninitialized data segments ( BSS )
  10. 程序的执行时regions and 堆(Heap) regions are also dynamically formed. 栈(Stack)

    In general, in a static image file, each part is called 节(Section) , and in the execution of the various parts called 段(Segment) . Assumptions are not specifically differentiated and can be collectively referred to as .

  11. The C language is 编译和连接后 generated 代码段 (Text), read-only data segments ( RO Data ), and read-write data segments ( RW Data ).

    In 执行时 addition to the above three regions, the uninitialized data segment () zone and the heap () zone BSS Heap and Stack () regions are included Stack .

7. Some examples
   Const CharRo[] = {"This was read only data"};//read-only data area    Static CharRw_1[] ={"This is global read write data"};//Read-write data segment initialized    Charbss_1[ -];//Uninitialized data segment    Const Char*ptrconst ="Constant Data";//string is placed in just reading the data segment    intMain () { Shortb//on the stack. Takes 2 bytes        Chara[ -];//Open 100 bytes on the stack, its value is its first address        Chars[]="ABCDEFG";//s on the stack, takes up 4 bytes, "ABCDEFG" itself is placed in a read-only data store, accounting for 8 bytes        Char*P1;//p1 on the stack. Takes 4 bytes        Char*p2="123456";//p2 on the stack. P2 point to the content can not be changed, "123456" in the Read Only data area        Static Charrw_2[]={"This is local read write data"};//locally initialized read-write data segment        Static Charbss_2[ -];//Partial uninitialized data segment        Static intc =0;//Global (Static) initialization zoneP1= (Char*)malloc(Ten*sizeof(Char) );//Allocate memory area in heap area        strcpy(P1,"xxxx");//"XXXX" is placed in the read-only data area. Accounted for 5 bytes         Free(p1);//Use free to release the memory pointed to by P1        return 0; }

The read-write data segment includes the global variable static char rw_1[] and the local static variable static rw_2[]. The difference is that when you make a Yi, it is used inside the function or in the entire file. For rw_1[] Whether or not static modifications are available. It will be placed in the read-write data area. Just whether it can be referenced by other files or not.

It's not the same for the latter. It is a local static variable. Placed in the read-write data area, assuming that there is no static modification, its meaning changes completely, it will be open in the stack space of local variables, rather than static variables. There is no specific value after rw_1[],rw_2[] here. Indicates that the static area size is the same as the subsequent string length.

For uninitialized data area bss_1[100] and bss_2[100]. The difference is that the former is a global variable. Can be used in all files; the latter is a local variable and is used only inside the function. Uninitialized data segments do not set the subsequent initialization values, so the size of the range must be specified using numeric values, and the Yi will set the length to be added in BSS based on size.

References
In-depth discussion of where local variables and global variables are stored in memory in C language
How to layout the memory of C programming program

How to layout the memory of C programming program

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.