当前位置:网站首页>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

边栏推荐
- Table table setting fillet
- 机器学习:随机梯度下降(SGD)与梯度下降(GD)的区别与代码实现。
- Ds-5/rvds4.0 variable initialization error
- shell脚本快速统计项目代码行数
- Appium automation test foundation uiautomatorviewer positioning tool
- 各种语言,软件,系统的国内镜像,收藏这一个仓库就够了: Thanks-Mirror
- POJ 3177 Redundant Paths POJ 3352 Road Construction(双连接)
- JS es5 peut également créer des constantes?
- 子网划分、构造超网 典型题
- Instructions for using the domain analysis tool bloodhound
猜你喜欢

子网划分、构造超网 典型题

1123. 最深叶节点的最近公共祖先

百度飞将BMN时序动作定位框架 | 数据准备与训练指南 (下)

LeetCode. 剑指offer 62. 圆圈中最后剩下的数

从底层结构开始学习FPGA----FIFO IP的定制与测试

Go zero micro service practical series (IX. ultimate optimization of seckill performance)

移植DAC芯片MCP4725驱动到NUC980

Clickhouse fields are grouped and aggregated, and SQL is queried according to the granularity of any time period

Instructions for using the domain analysis tool bloodhound

【C语言进阶篇】指针的8道笔试题
随机推荐
Curl command
C language instance_ two
WCF Foundation
Make Jar, Not War
剑指 Offer II 035. 最小时间差-快速排序加数据转换
[advanced C language] 8 written questions of pointer
AI 从代码中自动生成注释文档
【芯片方案设计】脉搏血氧仪
When grep looks for a process, it ignores the grep process itself
1123. The nearest common ancestor of the deepest leaf node
Drag to change order
1123. 最深叶节点的最近公共祖先
Basic introduction and use of dvajs
百度飞将BMN时序动作定位框架 | 数据准备与训练指南 (下)
Sword finger offer II 035 Minimum time difference - quick sort plus data conversion
JS ES5也可以創建常量?
编译命令行终端 swift
黑马笔记---创建不可变集合与Stream流
JS how to quickly create an array with length n
hdu 4661 Message Passing(木DP&amp;组合数学)