当前位置:网站首页>Four areas of telephone memory

Four areas of telephone memory

2022-06-21 17:25:00 Soy sauce;

1. Memory partition

Before you run

We want to execute what we write c Program , Then the first step is to compile the program .

  1. Preprocessing : Macro definition expansion 、 Header file expansion 、 Conditional compilation , The syntax is not checked here
  2. compile : Check grammar , Compile the preprocessed file to generate assembly file
  3. assembly : Generating assembly file into object file ( Binary )
  4. link : Link the object file as an executable

When we compile and generate the executable , We passed the linux Next size Command can view the basic information of an executable binary file :

You can see from the picture above , Before running the program , in other words Before the program is loaded into memory , The executable program has been divided internally 3 Segment information , Respectively Code section (text)、 Data area (data) And uninitialized data area (bss)3 Parts of ( Some people put data and bss Together, they are called static areas or global areas ).

        1. Code section

Deposit CPU Machine instructions executed . Usually, the code area can be share Of ( That is, other executors can call it ), The purpose of making it sharable is for programs that are frequently executed , You only need to have... In memory Just a copy of the code . The code area is usually read-only Of , The reason to make it read-only is to prevent the program from accidentally modifying its reference t Make . in addition , The code area also plans information about local variables .

        2. Global initialization data area / Static data area (data paragraph )( static state , overall situation , often )

This section contains the..., which is explicitly initialized in the program Global variables 、 Already initialized Static variables ( Including global static variables and const data ( Like string constants ).

        3. Uninitialized data area ( Also called bss  District )

The deposit is Global uninitialized variables and uninitialized static variables . The uninitialized data area is initialized by the kernel to 0 Or empty (NULL).

Generally speaking , After the program source code is compiled, it is mainly divided into two segments : Program instructions ( Code section ) And program data ( Data area ). Code segments belong to program instructions , And data field segments and .bss Segment belongs to program data .

So why separate program instructions from program data ?

  1. The program is load After it's in memory , Data and code can be mapped to two memory areas respectively . Because the data area is readable and writable to the process , The instruction area is read-only to the program , So after partitioning , The program instruction area and data area can be set to be readable, writable or read-only respectively . This prevents the program's instructions from being modified intentionally or unintentionally ;
  2. When multiple identical programs are running in the system , The instructions executed by these programs are the same , So you only need to save a copy of the program instructions in memory , It's just that the data in each program is different , This can save a lot of memory . Like before Windows Internet Explorer 7.0 After running , It needs to occupy 112 844KB Of memory , Its private part of the data is about 15 944KB, That is to say, there are 96 900KB Space is shared , If there are hundreds of such processes running in the program , It is conceivable that the sharing method can save a lot of memory .

  After running

Before the program is loaded into memory , Code area and global area (data and bss) The size of is fixed , The program cannot be changed during operation . then , Run executable , The operating system puts the physical hard disk program load( load ) To the memory , In addition to the information from the executable program to separate the code area (text)、 Data area (data) And uninitialized data area (bss) outside , There is also an additional stack area 、 Heap area .

        1. Code section (text segment)

It loads the executable code snippet , All executable code is loaded into the code area , This memory cannot be modified during operation .

        2. Uninitialized data area (BSS)

The executable is loaded BSS paragraph , The location can be separated or close to the data segment , Data stored in data segments ( Global not initialized , Static uninitialized data ) The life cycle of the program is the whole running process .

        

        3. Global initialization data area / Static data area (data segment)

The executable data segment is loaded , Stored in data segments ( Global initialization , Static initialization data , Literal constants ( read-only )) The life cycle of data is the whole process of program running .

        4. The stack area (stack) for example  int a=1;

Stack is an advanced memory structure , Release is automatically allocated by the compiler , Stores the parameter values of the function 、 Return value 、 Local variables, etc . Loading and releasing in real time during program running , therefore , The lifetime of the local variable is from applying to releasing the stack space . After the function executes, the local variable is released .

        5. Heap area (heap)

A heap is a big container , Its capacity is much larger than the stack , But there is no stack like the order of first in and last out . For dynamic memory allocation . The heap is in memory BSS Between area and stack area . Usually assigned and released by programmers , If programmers don't release , Recycle by the operating system at the end of the program .

  Related data types and their storage locations :

static and extern Focus on memory

type

Scope

Life cycle

Storage location

auto Variable

a pair {} Inside

The current function

The stack area

static local variable

a pair {} Inside

The whole running period of the program

Initialize at data paragraph , Not initialized at BSS paragraph

extern Variable

Whole procedure

The whole running period of the program

Initialize at data paragraph , Not initialized at BSS paragraph

static Global variables

Current file

The whole running period of the program

Initialize at data paragraph , Not initialized at BSS paragraph

extern function

Whole procedure

The whole running period of the program

Code section

static function

Current file

The whole running period of the program

Code section

register Variable

a pair {} Inside

The current function

The runtime is stored in CPU register

String constant

Current file

The whole running period of the program

data paragraph

2. Partition model  

The stack area

The memory is managed by the system . The main storage function parameters and local variables . After the function completes execution , The system releases the memory of stack area by itself , No need for user management .

matters needing attention : Do not return the local variable address , Local variables are released after the function body is executed , Another operation is illegal , The result is unknown .

#char* func(){// Do not return the local variable address , Local variables are released after the function body is executed , Another operation is illegal , The result is unknown .

char p[] = "hello world!"; // Store... In the stack area The statement

printf("%s\n", p);

return p;

}

void test(){

char* p = NULL;

p = func();  

printf("%s\n",p); 

}

Heap area

Manually requested by the programmer , Hand release , If not released manually , After the program is completed, it is recycled by the system , The life cycle is the entire program run time . Use malloc perhaps new Apply for a heap .

malloc apply free Release   Then point the pointer to null , Avoid wild pointer

matters needing attention : Null pointer in the calling function , The called function modifies an unsuccessful with a sibling pointer , There is no change p Of itself , Function will be passed into the newly opened space , To use a higher-level pointer to change its address for decoration .

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int * getSpace()
{
    int * p = malloc(sizeof(int)* 5);

    if (p == NULL)
    {
        return NULL;
    }

    for (int i = 0; i < 5;i++)
    {
        p[i] = i + 100;
    }
    return p;

}

void test01()
{
    int * p = getSpace();

    for (int i = 0; i < 5;i++)
    {
        printf("%d\n", p[i]);
    }

    // Data created manually in the heap , Remember to release manually
    free(p);
    p = NULL;

}


// matters needing attention
// If no memory is allocated to the pointer in the calling function , The calling function cannot modify the pointer in the calling function with the same level pointer
void allocateSpace( char * pp )
{
    char * temp =  malloc(100);
    if (temp == NULL)
    {
        return;
    }
    memset(temp, 0, 100);
    strcpy(temp, "hello world");
    pp = temp;

}

void test02()
{
    char * p = NULL;
    allocateSpace(p);

    printf("%s\n", p);
}


void allocateSpace2(char ** pp)
{
    char * temp = malloc(100);
    memset(temp, 0, 100);
    strcpy(temp, "hello world");
    *pp = temp;
}

void test03()
{
    char * p = NULL;

    allocateSpace2(&p);

    printf("%s\n", p);

    free(p);
    p = NULL;

}

int main(){
    //test01();
    //test02();
    test03();
    system("pause");
    return EXIT_SUCCESS;
}

Heap allocated memory API:

#include <stdlib.h>

void *calloc(size_t nmemb, size_t size);

function :

Allocate... In memory dynamic storage nmemb The block length is size A contiguous region of bytes .calloc Automatically allocate the allocated memory Set up 0.

Parameters :

nmemb: Number of memory units required

size: The size of each memory unit ( Company : byte )

Return value :

success : The starting address of the allocated space

Failure :NULL

#include <stdlib.h>

void *realloc(void *ptr, size_t size);

function :

Reassign malloc perhaps calloc Function allocates the size of memory space in the heap .

realloc It will not automatically clean up the increased memory , It needs to be cleaned by hand , If there is a continuous space after the specified address , Then it will add memory based on the existing address , If there is no space after the specified address , that realloc Will reallocate new contiguous memory , Copy the value of the old memory to the new memory , Free old memory at the same time .

Parameters :

ptr: For the previous use malloc perhaps calloc Allocated memory address , If this parameter is equal to NULL, So and realloc And malloc Consistent function

size: To reallocate the size of memory ,  Company : byte

Return value :

success : Newly allocated heap memory address

Failure :NULL

Sample code :

void test01(){

int* p1 = calloc(10,sizeof(int));

if (p1 == NULL){

return;

}

for (int i = 0; i < 10; i ++){

p1[i] = i + 1;

}

for (int i = 0; i < 10; i++){

printf("%d ",p1[i]);

}

printf("\n");

free(p1);

}

void test02(){

int* p1 = calloc(10, sizeof(int));

if (p1 == NULL){

return;

}

for (int i = 0; i < 10; i++){

p1[i] = i + 1;

}

int* p2 = realloc(p1, 15 * sizeof(int));

if (p2 == NULL){

return;

}

printf("%d\n", p1);

printf("%d\n", p2);

// Print

for (int i = 0; i < 15; i++){

printf("%d ", p2[i]);

}

printf("\n");

// Reassign

for (int i = 0; i < 15; i++){

p2[i] = i + 1;

}

// Print again

for (int i = 0; i < 15; i++){

printf("%d ", p2[i]);

}

printf("\n");

free(p2);

}

overall situation / Static zone ( Data area )

  • The variables in the global static area have allocated memory space and initialized in the compilation stage . The program in this block exists all the time , It mainly stores Global variables Static variables and Constant .

static state :static

matters needing attention :

  • Allocate memory before the program runs
  • The lifecycle dies before the file runs
  • It belongs to internal link property , Use... In the current file ( Normally, it is used in the current file )

Global variables :extern

matters needing attention :

  • The default global variable plus extern
  • It belongs to external link property , Tell the compiler that other files can be used ( An external command that cannot be resolved , Error in link phase )

Static variables and global variables

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

//1、 Static variables
static int a = 10;// Global scope

// characteristic : Initialize only once , Allocate memory at compile time , It belongs to internal link property , Can only be used in the current file

void test01()
{
    static int b = 20;
// Local static variable , The scope can only be in the current test01 in

    //a and b The life cycle of is the same
}


//2、 Global variables

extern int g_a = 100; // stay C Under the language Keywords are hidden in front of global variables  extern, It belongs to external link property

void test02()
{
    extern int g_b;
// Tell compiler g_b Is the external link attribute variable , Don't report an error when using this variable

    printf("g_b = %d\n", g_b);

}

int main(){
    test02();
    

    system("pause");
    return EXIT_SUCCESS;
}

Constant :

a.  const Constant decorated

matters needing attention :

  • const Decorated global variables , Assign to constant area ( read-only ) in  // direct / Indirect modification   Failure
  • const Modified local variables  // Assign to the stack , Not protected by the constant area ( Also known as pseudo constants )/ Failed to modify directly  // Indirect modification success     //C Under the language Called pseudo constant  
  • // Arrays cannot be initialized with pseudo constants

const Constant :

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

//1、const Decorated global variables , Even if the grammar passes , But the runtime is protected by the constant area , Run failed
const int a = 10; // Put it in the constant area

void test01()
{
    //a = 100; // direct / Indirect modification   Failure

    int * p = &a;
    *p = 100;

    printf("%d\n", a);

}

//2、const Modified local variables
void test02()
{
    const int b = 10; // Assign to the stack , Not protected by the constant area ( Also known as pseudo constants )
    //b = 100;   // Failed to modify directly


    // Indirect modification success
    //C Under the language Called pseudo constant

    int * p = &b;
    *p = 100;
    printf("b = %d\n", b);

    //int a[b];// Arrays cannot be initialized with pseudo constants

Be careful

(1) There is no distinction between initialized and uninitialized data areas , This is because variables in the static storage area are initialized if they are not displayed , The compiler will automatically initialize in the default way , That is, there are no uninitialized variables in the static storage area .

(2) Constants in the global static storage area are divided into constant variables and string constants , Once initialized , Do not modify the . Constant variables in static storage are global variables , Unlike local constants , The difference is that local constants are stored on the stack , Actually, it can be modified indirectly through pointers or references , The global constant is stored in the static constant area and cannot be modified indirectly .

(3) String constants are stored globally / Constant area of static storage . 

b. String constant

matters needing attention :

String constants are stored in the constant area , Modifying string constants is not allowed

For different compilers, the optimization of string constants is different

//3. String constant
void test03()
{
    char * p1 = "hello world";// All three are in one area
    char * p2 = "hello world";
    char * p3 = "hello world";

    printf("%d\n", p1);
    printf("%d\n", p2);
    printf("%d\n", p3);
    printf("%d\n", &"hello world");


    p1[0] = 'z'; // Modifying string constants is not allowed
    printf("%c\n", p1[0]);

}


int main(){
    //test01();
    //test02();
    test03();
    system("pause");
    return EXIT_SUCCESS;
}

Deepen the understanding

char* func(){

static char arr[] = "hello world!"; // Store in static area Can read but write

arr[2] = 'c';

char* p = "hello world!"; // overall situation / Static zone - String constant area

//p[2] = 'c'; // read-only , Do not modify the

printf("%d\n",arr);

printf("%d\n",p);

printf("%s\n", arr);

return arr;

}

void test(){

char* p = func();

printf("%s\n",p);

}

String constant Modifiable or not ? String constant optimization :

ANSI C Specified in the : Modify string constants , The result is undefined .

ANSI C There is no provision for compiler implementers to handle strings , for example :

1. Some compilers can modify string constants , Some compilers cannot modify string constants .

2. Some compilers treat multiple identical string constants as one ( This optimization can occur in string constants , Save a space ), Some do not do this optimization . If optimized , This may lead to the modification of one string constant and the change of other string constants , The result is unknown .

So try not to modify string constants

C99 standard :

char *p = "abc"; defines p with type ‘‘pointer to char’’ and initializes it to point to an object with type ‘‘array of char’’ with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

Whether the string constant addresses are the same

tc2.0, Same as the document Different string constant addresses .

Vs2013, The string constant address is the same for the same file and different files .

Dev c++、QT Same as file , Different files are different .

3. summary

Understanding C/C++ Memory partition error , The following terms are often encountered : Data area , Pile up , Stack , Static zone , The constant area , Global area , String constant area , Text constant area , Code area, etc , Beginners are confused . ad locum , Try to clarify the relationship between the above partitions .

The data area includes : Pile up , Stack , overall situation / Static storage area .
overall situation / Static storage includes : The constant area , Global area Static zone .
The constant area includes : String constant area Constant variable area .
Code section : Store the compiled binary code of the program , Non addressable area .

so to speak ,C/C++ There are only two memory partitions , Code area and data area .

原网站

版权声明
本文为[Soy sauce;]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211413401658.html