当前位置:网站首页>Part I - Fundamentals of C language_ 8. Memory management
Part I - Fundamentals of C language_ 8. Memory management
2022-07-21 18:55:00 【qq_ forty-three million two hundred and five thousand two hundr】
8.1 Scope
C The scope of language variables is divided into :
- Code block scope ( The code block is {} A piece of code between )
- Function scope
- File scope
8.1.1 local variable
Local variables are also called auto Automatic variable (auto Write but not write ), In general, code blocks {} Internally defined variables are automatic variables , It has the following characteristics :
- Define... In a function , Only valid within the scope of a function
- Define... In a compound statement , Only valid in compound statements
- As the function call ends or the compound statement ends , The declaration cycle of local variables also ends
- If there is no initial value , The content is random
#include <stdio.h>
void test()
{
//auto It's the same whether you write or not
//auto Can only appear in {} Inside
auto int b = 10;
}
int main(void)
{
//b = 100; //err, stay main No in scope b
if (1)
{
int a = 10; // Define... In a compound statement , Only valid in compound statements
printf("a = %d\n", a);
}
//a = 10; //err Leave if() The compound sentence of ,a No longer exists
return 0;
}
8.1.2 static state (static) local variable
- static The scope of local variables is also valid within the defined function
- static The life cycle of a local variable is the same as that of a program , meanwhile staitc The value of a local variable Initialize only once , But it can be assigned multiple times
- static If a local variable is not assigned an initial value , The system will assign value automatically : Numerical variables are automatically assigned initial values 0, Empty character of character type variable
#include <stdio.h>
void fun1()
{
int i = 0;
i++;
printf("i = %d\n", i);
}
void fun2()
{
// Static local variables , No assignment , The system is assigned as 0, And it's only initialized once
static int a;
a++;
printf("a = %d\n", a);
}
int main(void)
{
fun1();
fun1();
fun2();
fun2();
return 0;
}
8.1.3 overall situation Variable
- Define outside function , It can be shared by functions in this document and other documents , If functions in other files call this variable , Must use extern Statement
- The life cycle of a global variable is the same as that of a program
- Global variables of different files cannot have duplicate names
8.1.4 static state (static) overall situation Variable
- Define outside function , The scope is limited to the defined file
- Static global variables of different files can have the same name , But the scope does not conflict
- static The life cycle of a global variable is the same as that of a program , meanwhile staitc The value of the global variable is initialized only once
8.1.5 extern Global variable declaration
extern int a; Declare a variable , This global variable has been defined in other files , It's just a statement , Not the definition .
8.1.6 Global and static functions
stay C Functions in the language are global by default , Use keywords static You can declare a function as static , The function is defined as static This means that this function can only be used in the file that defines this function , Cannot call... In other files , Even declaring this function in other files is useless .
For... In different files staitc Function names can be the same .
Be careful :
- Allow the same variable name in different functions , They represent different objects , Assign different units , Mutual interference .
- In the same source file , Allow global and local variables to have the same name , In the scope of a local variable , Global variables don't work .
- All functions are global by default , It means that all functions cannot have the same name , But if it is staitc function , So the scope is file level , So different files static Function names can be the same .
8.1.7 summary
type | Scope | Life cycle | ||
auto Variable | a pair {} Inside | The current function | ||
static local variable | a pair {} Inside | The whole running period of the program | ||
extern Variable | Whole procedure | The whole running period of the program | ||
static Global variables | Current file | The whole running period of the program | ||
extern function | Whole procedure | The whole running period of the program | ||
static function | Current file | The whole running period of the program | ||
register Variable | a pair {} Inside | The current function | ||
Global variables | Whole procedure | The whole running period of the program |
8.2 Memory layout
8.2.1 Memory partition
C The code through Preprocessing 、 compile 、 assembly 、 link 4 Step to generate an executable program .
stay Windows Next , A program is a common executable , Below is a list of the basic information about a binary executable 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 is shareable ( That is, other executors can call it ), The purpose of making it sharable is for programs that are frequently executed , Just have a copy of the code in memory . Code areas are usually read-only , The reason to make it read-only is to prevent the program from accidentally modifying its instructions . in addition , The code area also plans information about local variables .
2. Global initialization data area / Static data area (data paragraph )
This area contains the global variables that are explicitly initialized in the program 、 Static variables already initialized ( Including global static variables and local static variables ) And constant data ( Like string constants ).
3. Uninitialized data area ( Also called bss District )
Stored are global uninitialized variables and uninitialized static variables . The uninitialized data area is initialized by the kernel to 0 Or empty (NULL).
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 system loads the program into 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)
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 .
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 .
8.2.2 Storage type summary
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 |
8.2.3 Memory manipulation function
1) memset()
#include <string.h>
void *memset(void *s, int c, size_t n);
function : take s The front of the memory area n Bytes in parameter c fill
Parameters :
s: Operation memory required s The first address
c: Filled characters ,c Although the parameter is int, But it has to be unsigned char , The scope is 0~255
n: Specify the size you want to set
Return value :s The first address
int a[10];
memset(a, 0, sizeof(a));
memset(a, 97, sizeof(a));
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%c\n", a[i]);
}
2) memcpy()
#include <string.h>
void *memcpy(void *dest, const void *src, size_t n);
function : Copy src The front of the memory content n Byte to dest On the memory address of the value .
Parameters :
dest: Destination memory first address
src: First address of source memory , Be careful :dest and src The memory space referred to cannot overlap , This may cause an error in the program
n: Number of bytes to copy
Return value :dest The first address
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int b[10];
memcpy(b, a, sizeof(a));
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d, ", b[i]);
}
printf("\n");
//memcpy(&a[3], a, 5 * sizeof(int)); // Memory overlap , Pay attention to the use at this time
3) memmove()
memmove() Functional usage and memcpy() equally , The difference lies in :dest and src Refers to when the memory space overlaps ,memmove() Still able to handle , But the execution efficiency ratio memcpy() lower .
4) memcmp()
#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);
function : Compare s1 and s2 The front of the memory area pointed to n Bytes
Parameters :
s1: Memory head address 1
s2: Memory head address 2
n: Before comparison n Bytes
Return value :
equal :=0
Greater than :>0
Less than :<0
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int b[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int flag = memcmp(a, b, sizeof(a));
printf("flag = %d\n", flag);
8.2.4 Heap memory allocation and release
1)malloc()
#include <stdlib.h>
void *malloc(size_t size);
function : Dynamic storage in memory ( Heap area ) Allocate a piece with a length of size A contiguous region of bytes , Used to store the type specified by the type specifier . The content of the allocated memory space is uncertain , In general use memset initialization .
Parameters :
size: Need to allocate memory size ( Company : byte )
Return value :
success : The starting address of the allocated space
Failure :NULL
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
int count, *array, n;
printf(" Please enter the number of arrays to apply for :\n");
scanf("%d", &n);
array = (int *)malloc(n * sizeof (int));
if (array == NULL)
{
printf(" Failed to apply for space !\n");
return -1;
}
// Apply to space clearance 0
memset(array, 0, sizeof(int)*n);
for (count = 0; count < n; count++) // Assign value to array
{
array[count] = count;
}
for (count = 0; count < n; count++) // Print array elements
{
printf("%2d", array[count]);
}
free(array);
return 0;
}
2)free()
#include <stdlib.h>
void free(void *ptr);
function : Release ptr A piece of memory space pointed to ,ptr Is a pointer variable of any type , Point to the first address of the released area . An error occurs when the same memory space is freed multiple times .
Parameters :
ptr: The first address that needs to free up space , The released area should be made up of malloc The area allocated by the function .
Return value : nothing
8.3 Memory partition code analysis
1) Return stack address
#include <stdio.h>
int *fun()
{
int a = 10;
return &a;// Function call completed ,a Release
}
int main(int argc, char *argv[])
{
int *p = NULL;
p = fun();
*p = 100; // Operation field pointer to memory ,err
return 0;
}
2) return data Area address
#include <stdio.h>
int *fun()
{
static int a = 10;
return &a; // Function call completed ,a Don't release
}
int main(int argc, char *argv[])
{
int *p = NULL;
p = fun();
*p = 100; //ok
printf("*p = %d\n", *p);
return 0;
}
3) Value passed 1
#include <stdio.h>
#include <stdlib.h>
void fun(int *tmp)
{
tmp = (int *)malloc(sizeof(int));
*tmp = 100;
}
int main()
{
int *p = NULL;
fun(p); // Value passed , Parameter modification does not affect the argument
printf("*p = %d\n", *p); //err, Operate the memory pointed to by the null pointer
return 0;
}
4) Value passed 2
#include <stdio.h>
#include <stdlib.h>
void fun(int *tmp)
{
*tmp = 100;
}
int main()
{
int *p = NULL;
p = (int *)malloc(sizeof(int));
fun(p); // Value passed
printf("*p = %d\n", *p); //ok,*p by 100
return 0;
}
5) Return heap address
#include <stdio.h>
#include <stdlib.h>
int *fun()
{
int *tmp = NULL;
tmp = (int *)malloc(sizeof(int));
*tmp = 100;
return tmp;// Return heap address , Function call completed , Don't release
}
int main()
{
int *p = NULL;
p = fun();
printf("*p = %d\n", *p); //ok
if (p != NULL) // Heap space , After use , Hand release
{
free(p);
p = NULL;
}
return 0;
}
边栏推荐
- 一种非极大值抑制(non_max_suppression, nms)的代码实现方式
- [translation] principles for designing and deploying extensible applications on kubernetes
- 第一部分—C语言基础篇_7. 指针
- Digital twin technology creates a visualization solution for smart mines
- 第一部分—C语言基础篇_10. 文件操作
- C language -- 24 Gobang
- RENIX_ IPv6 automatic configuration -- practical operation of network tester
- ESB结合UMC云平台开发说明
- Can messages in CAPL: declaration, sending and receiving
- Embedded learning: introduction to Cortex-M series chips
猜你喜欢
通用分页(分页代码的封装)
Zhongang Mining: four trends of fluorite industry development
LeetCode:1260. 二维网格迁移【一维展开+拼接】
Solution to field 'ID' doesn't have a default value error
Ctfhub information disclosure
Graylog distributed log component to improve the efficiency of log checking!
MySQL的MVCC详细理解(2022版)
STM32 DHT11温湿度传感器模块学习总结
自定义分页标签
Splicing of SRC variables in wechat applet pictures
随机推荐
ESB combined with UMC cloud platform development instructions
程序初学者推荐学哪种编程语言比较好?
生成二维码
What impact will Microsoft's closure of basic authentication have on enterprises and employees?
Day009循环结构(练习)
excel转json (树状结构)
Linux中安装Redis
Ctfhub information disclosure
golang拾遗:自定义类型和方法集
Apple released watchos 8.7 with bug fixes and security updates
resttemplate调用post\get
Orepa: Ali proposed a heavy parameter strategy with fast training. The memory is halved and the speed is doubled | CVPR 2022
Stm32 DHT11 temperature and humidity sensor module learning summary
The longest valid bracket of question 32 in C language. Implement with stack
STM32 DHT11温湿度传感器模块学习总结
Can messages in CAPL: declaration, sending and receiving
Machine learning univariate linear regression
哈夫曼树与哈夫曼编码的考点
How much has changed from new retail to community group purchase?
Golang collection: custom types and method sets