Advanced C language (learn malloc&calloc&realloc&free in simple dynamic memory management)

content

1. Why there is dynamic memory allocation

Second, the use of dynamic memory functions

1. malloc function

(1) Definition of malloc

(2) Precautions for malloc function

(3) Use of malloc function

2. calloc function

(1) Definition of calloc function

(3) Use of calloc function

3. realloc function

(1) Definition of realloc function

 (2) Notes on the realloc function

(3) Use of realloc function

Summarize


1. Why there is dynamic memory allocation

The memory development methods we currently master in C language are:

int val = 20;//在栈空间上开辟四个字节
char arr[10] = {0};//在栈空间上开辟10个字节的连续空间
 
要么创建个变量,要么创建个数组。
这样开辟出来的空间我们在使用的时候有时候会出现要么感觉空间过大,要么感觉空间过小,不够灵活。
所以我们需要一种使空间可以变大变小的方法,这时候就出现了动态内存开辟。

However, the above-mentioned way of opening up space has two characteristics:

1. The space development size is fixed.

2. When the array is declared, the length of the array must be specified, and the memory it needs is allocated at compile time. But the need for space is not limited to the above. Sometimes the size of the space we need can only be known when the program is running, and the way the array is compiled to open up space cannot be satisfied. At this time, you can only try to open up dynamic storage.

Second, the use of dynamic memory functions

First of all, we need to understand how data, variables, and functions are stored in memory, as shown in the following figure:

1. malloc function

(1) Definition of malloc

 

 This function requests a contiguous free space in memory and returns a pointer to this space.

(2) Precautions for malloc function

1. If the opening is successful, a pointer to the opened space is returned.

2. If the development fails, a NULL pointer is returned, so the return value of malloc must be checked.

3. The type of the return value is void*, so the malloc function does not know the type of space to be opened, and the user decides when it is used.

4. If the parameter size is 0, the behavior of malloc is undefined by the standard and depends on the compiler.

(3) Use of malloc function

code show as below:

#include<stdio.h>

//动态内存开辟
int main()
{
	//假设开十个整型的空间 -- 10*sizeof(int)
	int arr[10];//栈区
	//动态内存开辟
	int* p = (int*)malloc(10 * sizeof(int));
	//使用这些空间的时候
	if (p == NULL)
	{
		perror("main");//main:xxxxxxxxxxx(错误信息)
	}
	//使用
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*(p + i) = i;
	}
	for (i = 0; i < 10; i++)
	{
		printf("%d", p[i]);//p[i]-->*(p + i)
	}
	//回收空间
	free(p);//malloc函数要配合free函数使用,使用完之后要主动释放这块空间
	p = NULL;//释放完了之后要把p置成空指针
	return 0;
}

2. calloc function

(1) Definition of calloc function

The C language also provides a function called calloc, which is also used for dynamic memory allocation.

(2) Precautions for calloc function

1. The function of the function is to open up a space for num elements of size size, and initialize each byte of the space to 0.

2. The only difference from the function malloc is that calloc will initialize each byte of the requested space to all 0s before returning the address.

(3) Use of calloc function

code show as below:

#include<stdio.h>

//动态内存开辟
int main()
{

	int* p = calloc(10,sizeof(int));
	//使用这些空间的时候
	if (p == NULL)
	{
		return 1;
	}
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		printf("%d", p[i]);//p[i]-->*(p + i)
	}
	//回收空间
	free(p);//malloc函数要配合free函数使用,使用完之后要主动释放这块空间
	p = NULL;//释放完了之后要把p置成空指针
	return 0;
}

The print result is as follows:

It should be noted that there are two differences between the calloc function and the malloc function.

1. The parameter of the calloc function is two, and the parameter of the malloc function is one. 

2. If the malloc function does not initialize and prints out random values, the calloc function does not need to be initialized, and will initialize each byte of the requested space to 0 by default.

3. realloc function

(1) Definition of realloc function

The emergence of the realloc function makes dynamic memory management more flexible.

Sometimes we find that the space applied for in the past is too small, and sometimes we feel that the space applied for is too large. In order to use the memory at a reasonable time, we must flexibly adjust the size of the memory.

The realloc function can adjust the size of the dynamically allocated memory.

 (2) Notes on the realloc function

1.ptr is the memory address to be adjusted

2. The return value of the new size after size adjustment is the starting position of the memory after adjustment.

3. On the basis of adjusting the size of the original memory space, this function will also move the data in the original memory to the new space.

4. There are two situations when realloc adjusts the memory space:

Case 1 When it is case 1, to expand the memory, add space directly after the original memory, and the data in the original space does not change.

Case 2 When it is case 2, when there is not enough space after the original space, the expansion method is to find another continuous space of suitable size on the heap space to use. This function returns a new memory address. Due to the above two situations, the use of the realloc function should be paid attention to.

(3) Use of realloc function

#include<stdio.h>

//动态内存开辟
int main()
{

	int* p = calloc(10,sizeof(int));
	//使用这些空间的时候
	if (p == NULL)
	{
		perror("main");
		return 1;
	}
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*(p + i) = 5;
	}//这里需要P指向的空间更大,需要20个int空间的大小
	//realloc调整空间大小
	int* ptr = realloc(p, 20 * sizeof(int*));
	if (ptr != NULL)
	{
		p = ptr;
	}
	//回收空间
	free(p);//malloc函数要配合free函数使用,使用完之后要主动释放这块空间
	p = NULL;//释放完了之后要把p置成空指针
	return 0;
}

Summarize

This article only briefly introduces the definition, precautions and use of dynamic memory functions, as well as the free function used to release the space opened up by dynamic memory, and then set it to empty. If you have any questions about the article, you are welcome to ask questions. I will learn and correct with an open mind. The most important thing is to make progress together, grow together, and learn programming well.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324273586&siteId=291194637