How to realize the development of dynamic memory, detailed explanation of the functions of malloc, calloc, realloc, and free

Preface: I believe everyone is familiar with static memory development, such as the following two lines of code

int a = 0;   //在栈空间上开辟4个字节的空间
char b[10] = {
    
     0 };   //在栈空间上开辟10个字节的连续空间

They have the following characteristics:
1. The size of space opening is fixed.
2. When the array is declared, the length of the array must be specified in advance, and the memory it needs is allocated at compile time.

However, the demand for space is flexible and changeable. Sometimes the size of the space we need can only be known when the program is running, so the above method of creating space for the array at compile time cannot meet the demand. At this time, you can use dynamic memory to open up. The following will introduce several functions related to it and how to use it, so as to ensure that you can get started quickly at a glance.

malloc, calloc, realloc, free functions

Header file: #include<stdlib.h>
malloc function: open up a continuous dynamic memory space in the heap area.
calloc function: open up a continuous dynamic memory space in the heap area, and initialize each byte to 0 at the same time.
realloc function: adjust the dynamically allocated memory size.
free: It is extremely simple to use, you only need to use it at the end of the code to release the opened dynamic memory space, the usage form: it will free(开辟的动态内存空间的起始地址)not be explained separately below.

malloc

The introduction of cplusplus is as follows: (The picture below is for reference only, it doesn’t matter if you don’t understand it)

insert image description here

1. malloc仅有一个参数,就是需要开辟内存空间的大小(单位是字节), but it is an unsigned type, so it needs to be changed to the symbol type we need when using it.
2. If the space is successfully allocated, a pointer to the starting position is returned, and if the space is not allocated, a null pointer is returned.

Through graphics and code examples, it is clear at a glance:

insert image description here

#include<stdio.h>
#include<stdlib.h>   //不要忘了引用头文件
int main()        
{
	int* p = (int*)malloc(12);  //开辟一块12个字节的动态内存空间
 
	free(p);     //释放动态内存空间
	return 0;
}

This completes the development of dynamic memory, is it very simple?

How to use malloc

The malloc function opens up a continuous dynamic memory space. Is this very similar to the array we have learned before? Yes, it can be imagined as an array when actually used.
Please see the following code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    
    
	int* p = (int*)malloc(40);   //开辟40个字节的空间
	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		//进行赋值操作
		p[i] = i + 1;    //数组形式,与上一行意义相同
	}
	for (i = 0; i < 10; i++)
	{
    
    
		printf("%d ", p[i]);    //打印
	}
	free(p);   //释放动态内存空间
	p = NULL;  //对p置空,可以不加。
	return 0;
}

Print result:Here is the quote

calloc

It is similar to malloc, but has one more parameter, and will initialize each byte to 0.

The introduction of cplusplus is as follows: (The picture below is for reference only, it doesn’t matter if you don’t understand it)

Here is the quote
1. calloc has two parameters, the first parameter is the number of elements to open memory, the second parameter is the size of each element (in bytes)
2. If the space is successfully allocated, it will return a pointer to the start The pointer of the location, if the space allocation fails, a null pointer is returned.

How to use calloc

Therefore, it is similar to malloc, so there is no detailed introduction with pictures and texts. For those who don’t understand, please see the picture and text introduction of malloc.
Here is still the above code as an example:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    
    
	//仅此处进行了修改,开辟10个整型的动态内存空间,每个整型大小为sizeof(int)
	int* p = (int*)calloc(10,sizeof(int));

	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		p[i] = i + 1;
	}
	for (i = 0; i < 10; i++)
	{
    
    
		printf("%d ", p[i]);
	}
	free(p);
	p = NULL;
	return 0;
}

Output result:

realloc

The emergence of the realloc function makes dynamic memory management more flexible.
Sometimes we find that the previously applied space is too small, and sometimes we feel that the applied space is too large, so we will make flexible adjustments to the memory belt.

cplusplus is introduced as follows:

Here is the quote
1. The realloc function has two parameters, the first parameter is the dynamic memory address to be adjusted, and the second parameter is the new size after adjustment (in bytes) 2... If the
space is successfully opened, it will return a pointer to the adjustment The pointer of the starting position after that, if the space allocation fails, a null pointer will be returned.

How to use realloc

Here is still the above code as an example: we originally printed 1 ~ 10, if I want to print 1 ~ 15, and do not create a new dynamic memory, how to do it?

#include<stdio.h>
#include<stdlib.h>
int main()
{
    
    
	int* p = (int*)malloc(40);
	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		p[i] = i + 1;
	}
	
    //从此修改
	int* ptr = realloc(p, 60);  //添加了5个int型,则扩容至60个字节
	for (i = 10; i < 15; i++)
	{
    
    
		ptr[i] = i + 1;
	}
	for (i = 0; i < 15; i++)
	{
    
    
		printf("%d ", ptr[i]);
	}
	free(p);
	p = NULL;
	return 0;
}

Print result:
insert image description here

So far, the content of this chapter is over. What needs to be mentioned here is: because the focus of this chapter is how to realize dynamic memory development, so I have no judgment if the memory development fails, so as not to dazzle beginners. For the precautions when opening up dynamic memory, I will write a blog to explain it separately.

BB at the end of the article: If you have any questions, you can leave a message in the comment area. If you have any questions, you are welcome to point out in the comment area. The blogger will confirm the modification as soon as possible after seeing it. Finally, it is not easy to make, if it is helpful to friends, I hope to give some likes and attention.
insert image description here

Guess you like

Origin blog.csdn.net/qq_73390155/article/details/129871113