当前位置:网站首页>Standard C language 10
Standard C language 10
2022-07-24 03:19:00 【Luo CS】
Twenty-nine 、 Heap memory
What is heap memory
Is a memory segment of the process , Manually managed by the programmer
advantage : Large enough
shortcoming : Equivalent to other code snippets , Use of trouble
Why use heap memory
1. With the complexity of the program , More data
2. The application release of other memory segments is controlled , The application release of heap memory can be controlled , It can save memory in time
How to use heap memory
Be careful :C There are no statements in the language that control heap memory , Only use C Functions of the standard library
The header file
#include <stdlib.h>
void *malloc(size_t size);
function : Request from heap memory size Bytes of memory , The value of the requested memory is uncertain
Return value : Successfully return the first address of the requested continuous memory , Failure to return NULL
Be careful :void* stay C Universal pointer in language , It can be converted with any pointer type ,
But in c++ Cannot automatically convert to other types of pointers , You need to cast , Give Way c++ Compiler compatible
void free(void *ptr);
function : Free a heap memory
ptr: The first address of the heap memory to be freed
Be careful :free Release is just permission , The data will not be cleared completely ; Cannot release continuously , But it can be released continuously NULL
void *calloc(size_t nmemb,size_t size);
function : Request from heap memory nmemb fast size Byte size memory
Return value : Successfully return the first address of the requested continuous memory , Failure to return NULL
Be careful :calloc The requested memory will be initialized to zero , Velocity ratio malloc slow
void *realloc(void *ptr,size_t size);
function : You can change the existing heap memory size ,size It means resizing .
Return value : The new first address of the adjusted memory block , Be sure to receive the return value again , It may not be adjusted in the original position
If the original position cannot be adjusted :
1. Apply for a new memory that matches the size
2. Copy the data in the original memory
3. Free original memory , Returns the first address of the new memory
malloc Memory management mechanism
1. When the first time to malloc Application memory ,malloc Will request memory from the operating system , The operating system assigns 33 page (1 page =1024 byte )
Give the memory to malloc management , But it doesn't mean that you can cross the border , because malloc Other memory may be allocated to “ others ”,
This will produce dirty data .
2. There is a gap between each memory block (4~12 byte ), Part of it is for memory alignment ( Faster access ), There must be 4 Byte record
malloc Maintenance information for , This maintenance information determines the next malloc Where to allocate memory , If the maintenance information is destroyed , It will affect
The next time malloc perhaps free The process of .
Problems needing attention when using heap memory
Memory leak :
Memory can no longer be used , You can't release , If you need to use it again, you need to apply for memory again
then , Continue to repeat the above process , Over time, there is less and less memory available .
Be careful : Once the process ends, all resources belonging to the process will be recycled by the operating system
How to reduce memory leakage :( Who applies for release , Who knows who should be released )
How to determine , Locating memory leaks
1. View memory usage
win Task manager
Linux ps -aux command
2. With the help of code analysis tools mtrace, Check malloc and free Whether they appear in pairs
3. encapsulation malloc、free, Record request 、 Release the information into the log file
Memory fragments :
Memory that has been released but can no longer be used is called memory fragmentation , Due to the incongruity between the time of application and release .
It cannot be completely avoided, but can only be minimized .
How to reduce memory fragmentation :
1. Try to use stack memory
2. Don't apply frequently 、 Free memory
3. Try to apply for large blocks of memory to manage by yourself
Memory cleaning function
The header file :#include <strings.h>
void bzero(void *s,size_t n);
function : Clear a piece of memory into 0;
s: The first address of the memory block
n: Number of bytes of memory block
#include <string.h>
void *memset(void *s, int c,size_t n);
function : Set the memory block as c
s: The first address of the memory block
c: What you want to set up ASCII value
n: Number of bytes of memory block
Return value : The first memory address after successful setting
shortcoming : Application trouble 、 It is easy to generate memory fragmentation
advantage : It can be irregular 、 Low memory requirements
Heap memory defines a two-dimensional array
Pointer array :
Can define n That's ok ,m Column 2D array
type * arr[n];
for (int i = 0; i < n;i++)
{
arr[i] = malloc(m*sizeof( type ));
}
Be careful : In every line m Values can be different , In this way, irregular two-dimensional arrays can be defined .
Array pointer :
type (*arrp)[n] = malloc(sizeof( type )*n*m);
apply m That's ok n Two dimensional array of columns
shortcoming : High requirements for continuous memory , Maybe the application failed ;
advantage : The application is simple
Be careful : The so-called multidimensional arrays are actually simulated with one-dimensional arrays
边栏推荐
- Insist on accompanying study
- Basic knowledge of trigger (Part 2)
- Babylon.js cool canvas background animation JS special effects
- Minimum exchange times
- The former backbone of WPS spent 10 years building new software. Excel users: I switched to WPS for this
- Bingbing learning notes: basic operation of vim tool
- Is the reverse repurchase of treasury bonds safe? How to open an account online?
- Okaleido tiger NFT is about to log in to the binance NFT platform. Are you looking forward to it?
- Example of producer consumer code implemented by the destructor framework without lock
- [AMC] federal quantification
猜你喜欢

FTP服务与配置

Read and understand the advantages of the LAAS scheme of elephant swap

Basic knowledge of trigger (Part 2)

Simulink code generation: variable subsystem and its code

数据湖:Apache Hudi简介
![[MySQL learning] install and use multiple versions of MySQL, MySQL 8 and MySQL 5.7 at the same time, compressed version](/img/08/3765b34809cc4c723608f5d2e86ed4.png)
[MySQL learning] install and use multiple versions of MySQL, MySQL 8 and MySQL 5.7 at the same time, compressed version

Expressions régulières \ \ B \ \ b compréhension de l'appariement des limites des mots

Ugui source code analysis - stencilmaterial

什么是IMU?

Hcip day 9 notes (OSPF routing feedback, routing policy, and Configuration Guide)
随机推荐
The first edition of Niuke brush question series (automorphic number, return the number of prime numbers less than N, and the first character only appears once)
Expressions régulières \ \ B \ \ b compréhension de l'appariement des limites des mots
B. Eastern Exhibition- Codeforces Round #703 (Div. 2)
Industrial controller, do you really know your five insurances and one fund?
Lagrange polynomial
C. Minimum Ties-Educational Codeforces Round 104 (Rated for Div. 2)
数据湖:Apache Hudi简介
二分查找
Outlook client outlook.com mailbox setting method
Ugui source code analysis - maskablegraphic
Go IO operation - file read
Some properties of differential array operation
Ue5 split screen (small map) solution
How to realize software function safety
Connected graph (day 72)
Error code 0x80004005
SolidWorks cannot reference references
The error of van swipe in the rotation chart: cannot read a properties of null (reading width)
Minimum exchange times
C. Minimum Ties-Educational Codeforces Round 104 (Rated for Div. 2)