当前位置:网站首页>Dynamic memory management

Dynamic memory management

2022-06-30 07:20:00 There are fish in Beiming

1. Why is there dynamic memory allocation

The ways we have mastered to open up the continuous memory space are :

char arr[10] = {
    0};// Open up on the stack space 10 Bytes of contiguous space 

The above-mentioned way of opening up space has a very obvious defect , When an array is declared , You must specify the length of the array , The memory it needs is allocated at compile time , The space opened up is fixed , It may be too big , It may be small , It is difficult to meet our actual needs . At this point, you can only try dynamic memory allocation .

2. The introduction of dynamic memory function

We know that memory can be divided into bit stack areas , Heap area , Static storage area , The stack area mainly stores local variables and formal parameters , And we malloc,calloc,realloc The dynamically requested memory space is opened up in the heap area , meanwhile free The memory space released by the function is also the memory space of the heap , The static storage area mainly stores static variables and global variables .

Let's go into the dynamic memory function used to dynamically request space in the heap malloc,calloc,realloc.

(1)malloc and free

malloc The function is C Language provides a dynamic memory allocation function , Its prototype is void * malloc (size_t size);

This function applies to memory for a contiguous block of free space , And return the pointer to this space . If the development is successful , Returns a pointer to the opened space . If the development fails , Returns a NULL The pointer , therefore malloc The return value of must be checked . such as :

// Use malloc Function applied for a piece of memory space , Let the pointer ptr Point to this memory space 
ptr = (int*)malloc(num*sizeof(int));

// Later we want to use ptr when , Be sure to check if it is NULL
if(NULL != ptr)
{
    
	......
}

The type of return value is void* , Because malloc Function doesn't know the type of open space , The user will decide when using it .

If parameters size by 0,malloc The standard of behavior is undefined , It depends on the compiler .

C Language provides another function free, It is specially used for dynamic memory release and recovery , The function prototype is void free (void * ptr);

free Function is used to release memory opened dynamically . If parameters ptr The pointed space is not opened dynamically , that free The behavior of a function is undefined . If parameters ptr yes NULL The pointer , be free Functions do nothing .

It is worth noting that , Use free Function frees up the space for dynamic application , The pointer still holds the address of this space , That's the wild pointer , That is, we can still access the memory that has been reclaimed by the system through the pointer , But this constitutes illegal access , To avoid such illegal access , After we free this memory space , To assign a pointer to NULL.

free(ptr);
ptr = NULL;

notes :
Stack variables are automatically recycled , There is no need for us to manually release , Only malloc,calloc,realloc Dynamic application memory space is required free.

(2)calloc

calloc Function is also used for dynamic memory allocation , Its function prototype is void* calloc (size_t num, size_t size);

The function is for num Size is size The elements of open up a space , And initialize each byte of the space to 0. And functions malloc The only difference is calloc Initializes each byte of the requested space to full before returning the address 0.

 Insert picture description here
So if we need to initialize the content of the memory space applied , Then you can use calloc Function is very convenient to complete the task .

(3)realloc

realloc Functions make dynamic memory management more flexible .

Sometimes we find that the application space is too small in the past , Sometimes we think the application space is too large , In order to make rational use of memory , We must flexibly adjust the size of the memory , that realloc Function can be used to adjust the dynamic memory size . The function prototype is :
void* realloc (void* ptr, size_t size); among ptr Is the memory address to be adjusted ,size Is the new size after adjustment , The return value is the starting memory position after adjustment .

realloc There are two situations when adjusting memory space :

situation 1: There is enough space behind the original space
situation 2: There is not enough space after the original space
 Insert picture description here

When it's the case 1 When , To expand memory, add space directly after the original memory , The original spatial data does not change . When it's the case 2 When , There is not enough space after the original space , The way to expand is : Open up another continuous space of appropriate size on the heap space to use , At this time, the function will copy the data in the original memory to the newly opened space , This function returns a new memory address .

Of course, in addition to the above two cases , There's a third situation , Namely realloc The function failed to open up space and returned NULL, Because of the third situation ,realloc We should pay attention to the use of functions . for instance :

#include <stdio.h>
int main()
{
    
	int *ptr = malloc(100);
	if(ptr != NULL)
	{
    
		// Business processing 
	}
	else
	{
    
	  exit(EXIT_FAILURE);  
	}
	// Expand capacity 
	// Code 1
	ptr = realloc(ptr, 1000);// Is this ok? ?

Obviously, according to the above code 1 It is not advisable to write , because ptr It originally pointed to a piece of malloc Function opens up space , If realloc Function adjustment space failed , return NULL By ptr To receive the , that ptr The value is NULL, This leads me not only to fail to adjust the space , Even the space I pointed to was lost , In order to avoid this kind of situation, I lost my wife and lost my soldiers , We should make the code more rigorous .

// Code 2
	int*p = NULL;
	// Let's start with a pointer p To receive the return value 
	p = realloc(ptr, 1000);
	if(p != NULL)
	{
    
	// Confirm that the return value is not NULL after , We assign it to ptr
		ptr = p;
	}
	// Business processing 
	free(ptr);
	return 0;
}

It should be noted that ,realloc The message is NULL, The function is the same as malloc The function is the same , Directly open up a specified size of space , So realloc Space can be adjusted , It can also be like malloc Just like opening up space .

原网站

版权声明
本文为[There are fish in Beiming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/181/202206300713245720.html