当前位置:网站首页>Analyze "C language" [advanced] paid knowledge [End]
Analyze "C language" [advanced] paid knowledge [End]
2022-07-07 01:44:00 【Choice~】
List of articles
Dynamic memory development
malloc
Just extract a suitable piece of memory from the memory pool , It is not initialized , If initialization is needed , Either manually , Or use calloc function
Dynamic space ,2 Recovery methods
- Active release
- Program end
- Yes NULL Dereference of pointer
if(p==NULL) { printf(" error "); return ; }
- Memory cross-border access to dynamically opened space
- Use free Free up non dynamic space
- Use free Free a portion of dynamic memory
- For the same dynamic space , Multiple releases
- Forget to release the dynamically opened space , Can cause memory leaks
- Manual handle p Set to empty
p=NULL;
example
Void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
} Still bad
free(str);
str=NULL;
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, “hello”);
free(str);
if(str != NULL)
{
strcpy(str, “world”);
printf(str);
}
}// Memory access error , because free 了 , Though it hasn't disappeared , But I can't find the memory address , No access rights ; Still will enter if, Because there is no manual empty
The above example comes from 《 High quality C/C++ Programming 》
realloc
Compatibilization function : Copy the contents of the original block of memory to the new block , therefore , You can no longer use pointers to old memory , But use realloc The new pointer returned
return
In function return Only memory on the heap can be returned such as malloc Heap memory requested , and char p[]="hello world"; return p;//err
example :
int *p(void)
{
int x= 10;
return (&x);
}
Data storage
Big end and small end
Plastic surgery improves
#include<stdio.h>
int main()
{
//unsigned char 0-255
unsigned char a =200;
//00000000000000000000000011001000 -char One byte of a type is 8 position
//11001000
unsigned char b =100;
//00000000000000000000000001100100
//01100100
unsigned char c=0 ;
//a and b Shaping tips
//00000000000000000000000011001000
//00000000000000000000000001100100
//00000000000000000000000100101100
c = a + b;// Shaping is first raised and then added Will be truncated
//00101100
//00000000000000000000000000101100
//
printf("%d %d ",a+b, c);
// 300 44
return 0;
}
file
**#include< file name >** To the specified path provided by the system , Find file , If you can't find it , Just report a mistake
**#include" file name "** Go to the current path to find the file first , If it cannot be found, execute #include< file name > The process of , If you can't find , Just report a mistake
If you find the file , Just copy and paste the contents of the file #include Where the preprocessing instruction appears
The system specifies the path at :
gcc -E test.c -o test.i -v
#include “…” The search starts here :
#include <…> The search starts here :
/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include
/usr/local/include
/usr/include
End of search list .
The blue part is the path specified by the system , can cd /usr/include see
The standard error
0: The standard input
1: standard output
2: Standard error output
“>” Indicates redirection ,&2 Channel representing standard error output , therefore 1>2& Indicates that the standard output is redirected to the standard error output channel ;
and 1>2 Indicates that the standard output is redirected to a file named 2 In the file of .
The process of Compiling Files
1. Preprocessing : Preprocess the source file to generate a preprocessed file , Preprocessing CPP According to the preprocessing instruction ( Such as #include,#define etc. ) Insert the contents of the contained file into the program
gcc -E test.c -o test.i// You can view the compilation process , use vim test.i . There is a detailed process at the end
printf("ARE=%.2f\n",ARE(3+2));==> printf("ARE=%.2f\n",3.14 *(3+2)*(3+2));
2. compile : According to the preprocessing file , Compile to assembly language , Call the assembler to generate assembly code (.s file )
gcc -S test.s -o test.o
3. assembly : Call the assembler , Translate into machine language , Generate target file (.o file )
gcc -c test.s -o test.o
4. link : take test.o And runtime files , Link library functions , Call connector , Add the functions used in the program to the program , Generate executable files
gcc test.o -o test
precompile
Notes are generally in the form of #if 0…else …#endif Used to save to the preprocessing file
Precompiling is also called preprocessing . Precompiling is not compiling , But pre compilation processing . This operation is automatically completed by the system before formal compilation **. Precompiling is also called preprocessing . Precompiling is not compiling , But pre compilation processing . This operation is automatically completed by the system before formal compilation .
#define Define a preprocessing macro
#undef Cancel the definition of macro
#if Compile conditional commands in preprocessing , amount to C The grammatical if sentence
#ifdef Determine whether a macro is defined , If defined , Execute the following statement
#ifndef And #ifdef contrary , Determine whether a macro is undefined
#elif if #if, #ifdef, #ifndef Or the front #elif Condition not satisfied , execute #elif The following statement , amount to C The grammatical else-if
#else #if, #ifdef, #ifndef Corresponding , If these conditions are not met , execute #else The following statement , amount to C The grammatical else
#endif #if, #ifdef, #ifndef The end of these conditional commands .
defined And #if, #elif In combination with , Determine whether a macro is defined
define And typedef Extraction of
You should use typedef instead of #define To create a new type , Because the latter cannot handle pointer types correctly
#define pro_char char *
pro_char a,b;
// Correctly stated a, however b Is declared as a character
For operations without specific types
It cannot be dereferenced without a concrete type
Memory
Life cycle of variable
The life cycle of a variable is from the allocation of the variable address space to the release of the variable address space
A program is a file statically stored on disk , A program is a collection of instructions , The program does not run , There is no allocation of variable address space .
The description of the use of computer resources during the program running process is the process . Every time the same process runs, it is a process . When we type... On the command line ./ Executable file , The program starts to run .
The operation of the program is divided into two stages , Namely Load and execute . The program is first loaded into a specific address space , For example, global variables 、 Static local variables and functions …, We call it the symbol of a program . The specific address of the program symbol , It is already allocated during the loading phase . We call such a store Static storage area .
The program is loaded , find main function , Then start executing the program , In the process of execution , When you encounter a statement that defines an automatic local variable , The system automatically allocates space for these automatic local variables , Local variables were born . The region where these local variables are located is called ** Dynamic storage .** The addresses of these variables are automatically assigned by the system , When the compound statement of the function ends , Automatically free its address space . So it is called static allocation . There is another kind. , In the process of program execution , The size of the address space required by the program is uncertain , Programmers are required to follow the actual situation , Apply to the system , Such an allocated address space is called dynamic allocation .
When the program is executed , You need to load the executable program into memory ,CPU Read program instructions from memory
data type : First, find the address of the variable by its name , Then access the contents of the address space according to the type of the variable
static
Modify local variables : The life cycle of local variables becomes longer
Modify global variable : Changed the scope of the variable , Let static global variables only be used inside the source file where they are , The source file can no longer be used .
Modify function : Changed the link properties of the function
External link properties -> Internal link properties
#include<stdio.h>
void cout(void){
int i =0;
printf("cout i++=%d\n",i++);
return ;
}
// Static variables are assigned an initial value in the compiled value , The initial value of the automatic variable is assigned when the function is called , Every time you call it, you must reset the initial value
void cout_c(void){
static int i =0;// Static local variables
printf("cout i++=%d\n",i++);
return ;
}
int main()
{
int i;
for(i=0;i<5;i++)
cout();
for(i=0;i<5;i++)
cout_c();
return 0;
}
/* Running results : cout i++=0 cout i++=0 cout i++=0 cout i++=0 cout i++=0 cout i++=0 cout i++=1 cout i++=2 cout i++=3 cout i++=4
stay count In the function , Variable i Is an automatic local variable , Call to function count When , To allocate an address space ,
And set the initial value to 0, Then output the value , then i The value of , then , Function call completed , Variable i The address space of is also at the station ,
So when you call again , And then assign them ,….
So the output is always 0.countc Static local variables in functions , When the program loads , The address space of the program has been determined before its execution ,
And set its initial value to 0, When I call this function , First, the output i The value of is 0, And then i Self increasing ,i The value of becomes 1, Function call completed ,
The address space of an automatic local variable in a function is released , However, the address space of the static local variable is not released, so when calling again i The value of is 1, And then self increase ….
Until the whole program is finished , To release static local variables i Value .
Similarities and differences between static storage and dynamic variables **:
identical : All need to allocate memory
Different : Static variables are automatically assigned by the system , Release , The programmer cannot manually assign... While the program is running , It cannot be manually released during the operation of the program , Static variables are allocated in the stack
Dynamic variables are assigned manually by the programmer , Release , The programmer can manually assign... While the program is running , It can also be released manually during program operation , You can manually free the space of dynamic variables at any time during the execution of a function , There is no need to wait for the function to terminate , Static variables are allocated in the heap ( Linked list )
The operation of the program is divided into two steps :
1. load , Load the program from the hard disk into the address space
2. perform , find main The function starts executing
Before the program is executed , A variable or constant that has been assigned an address space , Stored in static memory
It exists all the time while the program is running
stay During the execution of the procedure , When that statement is executed, the address space is allocated to the variable , Stored in dynamic storage , Automatic system management
satic The declaration is followed by an internal , Use only in source files , Calls to internal functions are also not allowed
extern Extend the scope of variables
storage
Distribution for them ,….
So the output is always 0.countc Static local variables in functions , When the program loads , The address space of the program has been determined before its execution ,
And set its initial value to 0, When I call this function , First, the output i The value of is 0, And then i Self increasing ,i The value of becomes 1, Function call completed ,
The address space of an automatic local variable in a function is released , However, the address space of the static local variable is not released, so when calling again i The value of is 1, And then self increase ….
Until the whole program is finished , To release static local variables i Value .
Similarities and differences between static storage and dynamic variables **:
identical : All need to allocate memory
Different : Static variables are automatically assigned by the system , Release , The programmer cannot manually assign... While the program is running , It cannot be manually released during the operation of the program , Static variables are allocated in the stack
Dynamic variables are assigned manually by the programmer , Release , The programmer can manually assign... While the program is running , It can also be released manually during program operation , You can manually free the space of dynamic variables at any time during the execution of a function , There is no need to wait for the function to terminate , Static variables are allocated in the heap ( Linked list )
The operation of the program is divided into two steps :
1. load , Load the program from the hard disk into the address space
2. perform , find main The function starts executing
Before the program is executed , A variable or constant that has been assigned an address space , Stored in static memory
It exists all the time while the program is running
stay During the execution of the procedure , When that statement is executed, the address space is allocated to the variable , Stored in dynamic storage , Automatic system management
satic The declaration is followed by an internal , Use only in source files , Calls to internal functions are also not allowed
extern Extend the scope of variables
storage
边栏推荐
- AcWing 904. Wormhole solution (SPFA for negative rings)
- Right mouse button customization
- What does front-end processor mean? What is the main function? What is the difference with fortress machine?
- AcWing 344. Solution to the problem of sightseeing tour (Floyd finding the minimum ring of undirected graph)
- C语言实例_5
- json学习初体验–第三者jar包实现bean、List、map创json格式
- 736. LISP syntax parsing: DFS simulation questions
- Using the entry level of DVA in taro3.*
- 安利一波C2工具
- dvajs的基础介绍及使用
猜你喜欢
Appium foundation - appium inspector positioning tool (I)
According to the analysis of the Internet industry in 2022, how to choose a suitable position?
shell脚本快速统计项目代码行数
Right mouse button customization
移植DAC芯片MCP4725驱动到NUC980
JS reverse -- ob confusion and accelerated music that poked the [hornet's nest]
Baidu flying general BMN timing action positioning framework | data preparation and training guide (Part 1)
dvajs的基础介绍及使用
子网划分、构造超网 典型题
Let's see how to realize BP neural network in Matlab toolbox
随机推荐
剑指 Offer II 035. 最小时间差-快速排序加数据转换
AcWing 344. 观光之旅题解(floyd求无向图的最小环问题)
AcWing 1140. Shortest network (minimum spanning tree)
Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which
WCF Foundation
tansig和logsig的差异,为什么BP喜欢用tansig
Reptile practice (VI): novel of climbing pen interesting Pavilion
黑马笔记---异常处理
Taro2.* applet configuration sharing wechat circle of friends
AcWing 1148. 秘密的牛奶运输 题解(最小生成树)
AcWing 1142. 繁忙的都市 题解(最小生成树)
C language instance_ four
mysqlbackup 还原特定的表
Mysqlbackup restores specific tables
糊涂工具类(hutool)post请求设置body参数为json数据
Appium基础 — Appium Inspector定位工具(一)
子网划分、构造超网 典型题
Yunna | work order management measures, how to carry out work order management
dvajs的基础介绍及使用
盒子拉伸拉扯(左右模式)