Explanation of dynamic memory management malloc, calloc, realloc and free functions in C language

Table of contents

1. Why does dynamic memory management exist:

2. Introduction to dynamic memory functions:

1. Dynamically open function-malloc function

1.1. Function declaration and function:

1.2. Function usage examples:

2. Release dynamic space function-free function

2.1. Notes on free function:

2.2. Free function usage examples:

3. Dynamically open function-calloc function

3.1. Declaration and function of function:

3.2. Function usage examples:

4. Dynamic development function-realloc (the most important and commonly used):

4.1. Notes:

4.2. Function declaration and function:

4.3. Function return value: there are three situations

4.4. Function usage examples:


1. Why does dynamic memory management exist:

We know that there are two ways to apply for memory space before: (variables and arrays)

But both methods have several drawbacks :

①: The space opening size is fixed;

②: When an array is declared, the length of the array must be specified, and the memory it requires is allocated at compile time;

However, due to space requirements, not only the above two situations, sometimes the amount of space we need is not known until the program is running, so the way to open up space during compilation of the array is not appropriate.

Suppose the array size is 100, but 101 elements cannot fit in it; only 10 elements are a waste of space.

So you can only try dynamic allocation at this time.

2. Introduction to dynamic memory functions:

1. Dynamically open function-malloc function

1.1. Function declaration and function:
void* malloc (size_t size);

①: Function function: Apply for an available continuous space in the memory, and the return value is the starting address of this space;

②: Function parameter: The type is size_t, that is, the function applies for size bytes of space at a time, but does not initialize the space content. If size==0, then the behavior of malloc is undefined and depends on the compiler;

③: The return value is void*, and the return rules are as follows:

④: This function is included in the header file <stdlib.h>.

⑤: The application space for dynamic memory functions is applied in the heap area , as shown below:

1.2. Function usage examples:
#include<stdio.h>
#include<stdlib.h>

int main()
{
	//要什么类型的空间,就用什么类型的指针接收
	//注意函数返回值为void*,所以记住强制类型转换
	int* p = (int*)malloc(40);
	//判断申请空间是否成功
	if (p == NULL)
	{
		perror("malloc");//打印申请失败的原因
		return 1;
	}
    //使用空间
	int i = 0;
	for (i = 0; i < 4; i++)
	{
		p[i] = i;
		printf("%d ", p[i]);
	}
	return 0;
}

2. Release dynamic space function-free function

Note: These dynamically allocated functions apply for memory space. When the program exits, it will be returned to the operating system. However, when the program does not exit, the dynamically allocated memory will not be automatically released. At this time, the function free() needs to be used to release it.

2.1. Notes on free function:

①: Function declaration:

void free (void* ptr);

②: This function is included in the header file <stdlib.h>.

2.2. Free function usage examples:

The method of using this function is very simple. The parameters only need to be dynamically opened variables, as follows:

It is worth noting here that after the free function releases the space, it will not change the value of the pointer p, so p still points to this space at this time, but the space has been released, so p is a wild pointer at this time, so we need to The pointer is left blank .

3. Dynamically open function-calloc function

3.1. Declaration and function of function:
void* calloc (size_t num, size_t size);

①: The function of the function: This function dynamically opens up num spaces of size size , and initializes each byte of the space to 0;

②: The return value is the same as malloc. If the development is successful, the starting address of this space will be returned; if the development fails, NULL will be returned.

③: The difference from the malloc function is that this function initializes each byte of the space to 0.

④:

3.2. Function usage examples:

int main()
{
	//动态开辟五个整型大小的空间
	int* p = (int*)calloc(5, sizeof(int));
	//检查是否开辟成功
	if (p == NULL)
	{
		perror("calloc");
		return 1;
	}
	//使用空间
	for (int i = 0; i < 5; i++)
	{
		printf("%d ", p[i]);
	}
	//释放空间
	free(p);
	p = NULL;
	return 0;
}

operation result:

4. Dynamic development function-realloc (the most important and commonly used):

4.1. Notes:

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

Sometimes we find that the space we applied for in the past was too small, and sometimes we feel that the space we applied for is too large. In order to use the memory reasonably, we can use the realloc function to dynamically open up the memory to flexibly adjust the memory size.

4.2. Function declaration and function:
void* realloc (void* ptr, size_t size);

①: Parameter introduction:

The first parameter void* refers to the space that needs to be resized, which was previously opened through the malloc, calloc, and realloc functions;

The second parameter size_t szie refers to the new space size after adjustment, in bytes;

②: When the first parameter ptr is a null pointer, the effect is the same as malloc.

4.3. Function return value: there are three situations

Case 1: If there is enough continuous space after str, the return value is the starting space of str.

Case 2: If there is not enough continuous space behind str, the realloc function will find a new space that is large enough; copy the contents of the old space to the new space; then release the old space; and finally return the starting address of the new space .

Case 3: Development fails and NULL is returned.

4.4. Function usage examples:
int main()
{
	//先用malloc开辟5个整型的空间
	int* p = (int*)malloc(20);
	//检查malloc是否开辟成功
	if (p == NULL)
	{
		perror("malloc");
		return 1;
	}
	//开辟成功后,赋值1,2,3,4,5
	int i = 0;
	for (i = 0; i < 5; i++)
	{
		p[i] = i + 1;
	}
	//用realloc扩容五个整形的空间,所以新空间为40字节
	//注意这里别用上面的指针p接收,
	//因为如果realloc开辟失败,就会返回空指针给指针p
	//指针p改变了,那么之前动态开辟的空间就找不到了,就会存在内存泄漏
	int* str =(int*) realloc(p, 40);
	//检查是否开辟成功
	if (str == NULL)
	{
		perror("realloc");
		return 1;
	}
	//开辟成功后再赋值给指针p,然后将str置零
	p = str;
	str = NULL;
	//检测是否将旧空间的数据拷贝到新空间
	for (i = 0; i < 5; i++)
	{
		printf("%d ", p[i]);
	}
    //释放
    free(p);
    p = NULL;
	return 0;
}

operation result:

This knowledge ends here, the knowledge about dynamic memory is not over yet, to be continued!

Guess you like

Origin blog.csdn.net/hffh123/article/details/133324322