当前位置:网站首页>Memory ==c language 1
Memory ==c language 1
2022-07-07 10:04:00 【Brother Dong's cultivation diary】
One 、 Why do programs need memory to run
1、 The purpose of a computer program is
- Results and processes : Use functions as analogies , The formal parameters of a function are the data to be processed , Function ontology is code , The return value of the function is the result , The execution process of a function is a process .
- Code example :
int add(int a,int b){ // This function is executed to get the result return a+b; } void add(int a,int b{ // The execution of this function focuses on the process int c ; c=a+b; printf("c=%d\n",c); return c; } int add(int a,int b){ // The execution of this function focuses on the process , Focus on results int c; c=a+b; printf("c=%d\n",c); return c; }
2、 The running process of a computer program
- The running process of a computer program is the process in which multiple functions in the program run successively , The process of function operation is the process of data processing .
3、 Von Neumann structure and Harvard structure
- Von Neumann structure : Data and code together , Together .(x86)
Harvard structure : Data and code are placed separately , Independent addressing .(ARM) - Code : It's a function
data : Global variables 、 local variable - Example : stay S5PV210 Running in Linux On the system , When running the application , All the application code and data are placed in DRAM in , This is the von Neumann structure ; In a single chip computer , We burn the program to Flash in . Then the program is Flash Running in the Central Plains , The data involved in the program ( Global variables 、 local variable ) Can't put Flash in , Must be on RAM(SRAM) in , This is the Harvard structure .
4、 Dynamic memory DRAM And static memory SRAM
- (1) DRAM The storage principle of is the way that capacitors store charge ,SRAM The storage principle of is the way of trigger .
- (2)SDRAM: Synchronous dynamic random access memory .
5、 Why do programs need memory to run ?
- Memory is used to store data ( And code ), Global variables 、 Local variables, etc , And data is the component and processing object of the program , Therefore, memory is the essential requirement of program operation . The simpler the program, the smaller the memory it needs to run , The more complex the program, the more memory it needs to run .
- Memory management is a very important knowledge point of programming , We learn many key points of programming for memory management , For example, data structures and algorithms .
6、 Think deeply : How to manage memory
- From the perspective of operating system :
- The operating system holds all the hardware resources , Because there's a lot of memory , So the operating system divides the memory into pages ( That is, the block , It's usually 4KB), Then manage it in pages . The page is managed in bytes . In fact, the principle of operating system memory management is very complex , But for programmers , Just make good use of the memory management provided by the operating system API that will do . For example, in C Used in language malloc、free To apply for and release memory
- Without operating system , The program needs to operate memory directly , Programmers need to calculate and arrange memory by themselves .
- From the perspective of programming language : Different languages provide different memory management interfaces
- ① assembly : There is no memory management , Memory management depends on the programmer himself , Directly use memory address when operating memory , Very trouble
- ②C Language : The compiler helps us directly manage memory addresses , Access memory through the variable name provided by the compiler , If you need a large block of memory under the operating system, you can use API(malloc、free) To access system memory , And bare metal programs need large blocks of memory, and need to define their own data to solve .
- ③c++: The use of memory is further encapsulated , We can use new To create objects ( It's just about allocating memory for objects ), Use after use delete To delete objects ( That is, freeing up memory ). therefore c++ Better memory management than c The language is more advanced , But memory management still needs to be implemented by programmers , Not releasing after use will cause memory leakage .
- ④java/c# etc. : These languages do not manipulate memory , Instead, the memory is manipulated through a virtual machine . Virtual machine as our programmer's agent , Help us deal with memory release .
- summary :java/c# It seems better than c/c++ More advanced , But the memory recycling of virtual machine needs to pay a certain performance price , When we care about the speed of developing programs , Will use java/c# Other languages ; When we are very concerned about the performance of the program , Will use c/c++.
Two 、 position 、 byte 、 Half word 、 Word concept and memory bit width
1、 What is memory ?
- ① Hardware angle : Memory is actually an accessory of a computer ( Memory module ). According to different implementation principles , Memory can be divided into SRAM and DRAM(SDRAM\DDR1SDRAM\DDR2SDRAM、LPDDR5SDRAM)
- ② Logical angle : Can read and write at random ( Given an address, you can access ); Memory is naturally used to store variables in programming ,c A variable of language corresponds to a small segment in memory .
2、 Logical abstraction diagram of memory
- Logically, memory is composed of infinite small lattices , Each small grid corresponds to an address
- In reality, the memory size is limited , for example 32 Bit operating system (32 Bit system means 32 Bit data line , But the general address line is also 32 position , That is, the memory address is only 32 Bit binary number , So the logical size is 2^32) The memory limit is 4GB. actually 32 The memory in the bit system is less than or equal to 4GB Of .
3、 Bits and bytes 、 Words and half words
- The unit of memory unit size is 4 individual : position (1bit) byte (8bit) Half word ( It's usually 16bit) word ( It's usually 32bit)
4、 Memory bit width
- In terms of hardware : The hardware implementation of memory itself has width , Some memory modules are 8 Bit , Some are 16 Bit . It should be emphasized that memory chips can be connected in parallel , Through parallel connection 8 Bit memory chip can realize 16 Bits or 32 Bit of memory .( Digital circuit has mentioned this knowledge )
- Logically speaking : The memory bit width is logically arbitrary , But the actual hardware bit width is not arbitrary , So we need to program according to the hardware characteristics of different bit widths
- Memory bit width is the number of bits of data that can be transferred in a clock cycle , The larger the number of bits, the larger the amount of data that can be transmitted instantaneously , This is one of the important parameters of memory
3、 ... and 、 Memory addressing 、 Memory alignment
1、 Memory addressing method
- The memory unit and address are uniquely 、 Bind forever .
- Address and space are two aspects of a memory unit .
2、 The key : Memory addressing is in bytes
3、 The relationship between memory and data type
- c The data types in the language are char、short、 int 、long、 float 、double.
- Data types are used to define variables , Variables need to be stored in memory , So the data type must match the memory to get the best performance .
- stay 32 The best way to define variables in bit system is to use int, Because it's efficient . The reason is that the system itself is 32 Bit structure , A processing 32 Bit data . stay 32 Defined in the bit system bool Type variables are also used inside the system int Realized .
- In actual programming, we should choose between memory and efficiency according to the actual situation .
4、 Memory alignment
- Alignment access works well with hardware , So it's very efficient ;
- Non aligned access is not compatible with hardware , So the efficiency is not high
Four 、C How language operates memory
1、C Language encapsulates memory address
- Use variable names to access memory
- What data types mean : Represents the length and parsing method of a memory lattice
- A function is an encapsulation of a piece of code , The essence of function name is the first address of this code , So the essence of function name is also a memory address .
2、 Using pointers to access memory indirectly
- About type , Whether ordinary variable type or pointer variable type , Just remember that : Type is only for the following numbers or symbols ( Represents the memory address ) The length and parsing method of the memory represented
3、 Using arrays to manage memory
- There is no essential difference between array management memory and variables , It's just that symbols are analyzed in different ways .
- The first element in the array is called the first element , The address of the first byte of the first element is the first address of the first element .
5、 ... and 、 The structure of memory management
1、 The significance of data structure
- Data structure is to study how data is organized in memory 、 Processing knowledge .
2、 Simplest data structure : Array
- Organize variables of the same type , Easy to manage .
- advantage : Store in memory in order , Subscripts are available for random access .
Inferiority : All elements must be of the same type , When defining, the size must be given and cannot be modified .
3、 The structure is on the stage
- Structure was invented to solve the first defect of array : All elements in an array must be of the same type .
- Code example :
struct people{
int age;
char name[10];
int height;
};
4、 Digression : Embedded pointer in the structure to realize object-oriented ( node )
- Process and object oriented : Process oriented refers to the step-by-step splitting of problem solving steps , As required , Finally solve the problem ; Object-oriented is to decompose the problem transaction into various objects , Classification to solve problems .
- C Languages are process-oriented , but C Written in language Linux The system is object-oriented .
- In a non object-oriented language , It's not necessarily impossible to implement object-oriented code , It's just easier to use object-oriented language to realize object-oriented , Because language itself does a lot of work .
- Code example :
struct s{
int age;// Common variables
int(*pfunc)(void);// A function pointer , Point to int xxx(void) Such functions
}
// Using such a structure can realize object-oriented , In this way, the structure containing function pointers is similar to that in object-oriented class
6、 ... and 、 Memory management stack (stack)
1、 What is stack? ?
- A stack is a data structure ,C Stack is used in language memory management to save function parameters and local variables .
2、 The characteristics of stack managed memory ( Small memory 、 automation )
- First in, then out (FILO), And the queue is first in, first out (FIFO).
- The characteristic of stack is that the entrance is the exit , There's only one mouth , The other one is blocked , So it's first in, then out . The characteristic of the queue is that there are both entrances and exits , You have to go in through the entrance , Come out of the exit , So it's first in, first out .
3、 Examples of stack applications : local variable
- c Local variables in language are implemented by stack , Defining local variables , The corresponding operation is stack ( automation );
When the function exits the local variable logout , The corresponding operation is stack ( automation ). - The advantages of stacks : convenient 、 Neither allocation nor recycling need to be operated by programmers ,c Language is done automatically
- Define local variables but not initialized , Values are random , Why? ?
Because the trestle is used repeatedly , And it is not cleared after each use
4、 Advantages and disadvantages of stack
- advantage : automation , There is no need for programmers to manually operate memory
- Inferiority : First , The trestle has sizes , So the stack memory size is not easy to set . So it's too small to overflow , Too big to waste memory ( Similar to arrays ). secondly , Stack overflow is very harmful , Be sure to avoid . So we are C You can't define too many or too large local variables in a language ( For example, we cannot define int a[10000]; When using recursion to solve problems, we must pay attention to recursive convergence ).
7、 ... and 、 Heap of memory management (heap)
1、 What is a heap
- Heap is a way of memory management , Its characteristic is freedom ( Apply at any time 、 Release 、 The size of the block is arbitrary )
- Heap memory is the partition of the operating system to the heap manager ( A piece of code for the operating system , Belongs to the operating system memory management unit ) To manage , And then to the user ( User process ) Provide API(malloc and free) Heap to use .
- When do I need to use heap memory ?
When the memory capacity is large 、 When it needs to be used and released repeatedly , A lot of data structures ( Like linked lists ) The use of requires the use of heap memory .
2、 Characteristics of heap memory management
- Unlimited capacity ( Regular needs can be met ).
- Both application and release need to be done manually , If it is not released after use, it will cause memory leakage , The accumulation of memory leaks will lead to memory overflow and even system crash .
- ( Memory leak : apply (new/malloc) I got a piece of memory , But there is no manual release (delete/free) Memory , As a result, the pointer has disappeared , And what the pointer points to is still , Can't control this memory )
3、C Language operation heap memory interface
- (1) There are three functions with similar functions when applying for heap memory :malloc、calloc、realloc.
- void *malloc(size_t size); // Request a specified amount of memory
- void *calloc(size_t nmemb, size_t size); // apply nmemb Memory units , Every size byte
- void *realloc(void *ptr, size_t size); // Change the size of the space already requested
- (2) Heap memory release is the simplest , Call directly free Function
void free(void *ptr); - (3) Code example :
// For example, to apply for 10 individual int Element memory
malloc(40);
calloc(10,4);
- (4)C The number of array elements must be given when the language defines an array , And can no longer be modified . And in the Java In advanced languages , You can modify the size of the array , The principle is to recreate a new array , Then release the original array .realloc The implementation principle of is similar .
4、 Advantages and disadvantages of heaps
- advantage : Flexible use
- Inferiority : Programmers need to deal with details such as release , It's easy to make mistakes , Rely heavily on programmer level .
8、 ... and 、 Complex data structures
1、 Linked list 、 Hashtable 、 Binary tree 、 Map, etc.
- Linked list : Linked list is the most important ,Linux Linked lists are often used in the kernel , The writing of drivers and applications often requires linked lists , So you must master the linked list : Definition of structure , Creation of linked list , Addition of linked list 、 Delete 、 check , The reverse order of the linked list
- Hashtable : Not very often , Generally, you don't need to realize it yourself , There are many hash tables directly implemented by others . We need to understand the principle of hash table 、 characteristic 、 Applicable scenario .
- Binary tree 、 Map, etc. : Used to deal with specific problems , Rarely used , Don't get too tangled up .
2、 Why more complex data structures are needed
- Because there are many practical problems in reality , Specific problems may require specific data structures and algorithms to solve .
3、 The relationship between data structure and algorithm
- The invention of data structure is to cooperate with a certain algorithm , The algorithm is to deal with specific problems , Its implementation depends on specific data structures
4、 How to learn data structure and algorithm
- The data structure is consistent with the algorithm , We should study together .
- Data structure and algorithm are not all the key points for embedded , Don't study blindly .
5、 give an example
- Linux When the kernel manages character device drivers , Hash table used (hash table, Hash table ), Therefore, many characteristics of character device driver are related to the characteristics of hash table .
边栏推荐
- Sword finger offer II 107 Distance in matrix
- Performance optimization record of the company's product "yunzhujia"
- Become a "founder" and make reading a habit
- web3.0系列之分布式存储IPFS
- 2016 CCPC Hangzhou Onsite
- flinkcdc采集oracle在snapshot阶段一直失败,这个得怎么调整啊?
- Use 3 in data modeling σ Eliminate outliers for data cleaning
- ViewPager2和VIewPager的區別以及ViewPager2實現輪播圖
- Database multi table Association query problem
- Liunx command
猜你喜欢
Internship log - day07
Win10安装VS2015
Natapp intranet penetration
Performance optimization record of the company's product "yunzhujia"
iNFTnews | 时尚品牌将以什么方式进入元宇宙?
CentOS installs JDK1.8 and mysql5 and 8 (the same command 58 in the second installation mode is common, opening access rights and changing passwords)
Sqlplus garbled code problem, find the solution
Garbage disposal method based on the separation of smart city and storage and living digital home mode
Lesson 1: finding the minimum of a matrix
Detailed explanation of diffusion model
随机推荐
2020ccpc Weihai J - Steins; Game (SG function, linear basis)
Flex flexible layout
AI从感知走向智能认知
Addition, deletion, modification and query of ThinkPHP database
[untitled]
Lesson 1: finding the minimum of a matrix
官媒关注!国内数字藏品平台百强榜发布,行业加速合规健康发展
C# XML的应用
20排位赛3
China's first electronic audio category "Yamano electronic audio" digital collection is on sale!
Detailed explanation of diffusion model
Do you have a boss to help look at this error report and what troubleshooting ideas are there? Oracle CDC 2.2.1 flick 1.14.4
用flinksql的方式 写进 sr的表,发现需要删除的数据没有删除,参照文档https://do
Agile course training
洛谷P2482 [SDOI2010]猪国杀
ORM--分组查询,聚合查询,查询集QuerySet对象特性
The industrial chain of consumer Internet is actually very short. It only undertakes the role of docking and matchmaking between upstream and downstream platforms
Delete a record in the table in pl/sql by mistake, and the recovery method
请教个问题,我用sql-client起了个同步任务,从MySQL同步到ADB,历史数据有正常同步过去
高斯消元