[C Language Improvement] In-depth understanding of dynamic memory management

Table of contents

1. Static allocation and dynamic allocation 

Two, memory management function

1. malloc applies for heap space

2. calloc applies for heap space

3. Free reclaims heap space permission

4. memset memory setting function

5. realloc memory increase and decrease function

3. Memory leak (understand)


1. Static allocation and dynamic allocation 

1. Static allocation

In the process of program compilation or operation, the allocation method of allocating memory space according to the predetermined size. such as int a[10]

The size of the required space must be known in advance.

Allocated in the stack area or global variable area , generally in the form of an array.

2. Dynamic allocation

During the running of the program, the required space can be allocated freely according to the required size.

Allocate as needed.
Allocated in the heap area , generally using a specific function for allocation.

Two, memory management function

        The C language provides some memory management functions to dynamically allocate and reclaim memory space on demand.

1. malloc applies for heap space

Allocate a continuous area of ​​size bytes         in the dynamic storage area (heap area) of memory to store the type specified by the type specifier. The function prototype returns a void* pointer, and the corresponding type conversion must be performed when using it . The content of the allocated memory space is uncertain , and it is generally initialized with memset .

Header file: #include<stdlib.h>

Usage: void * malloc(size_t size);//size indicates the number of bytes of space requested, void *(universal pointer)

The return value of the function is successful : the return space start address

                      Failed : NULL

Features: The heap space requested by malloc needs to use memset to clear the original content, that is, it will not be automatically cleared

2. calloc applies for heap space

Header file: #include<stdio.h>

用法:void *calloc(size_t nmemb, size_t size);

nmemb: the number of blocks of memory

size: the number of bytes per block

The function return value is successful : return the start address of the heap space

           Failed : NULL

calloc will automatically clear the requested space to 0

3. Free reclaims heap space permission

Header file: #include<stdlib.h>

Usage: void free(void *ptr);

ptr is the starting address of the heap space that needs to be released

If the space is not reclaimed by free, all the requested space will be reclaimed when the process ends.

Practical application example: apply for a dynamic array of n elements

malloc(n*sizeof(int));

calloc(n, sizeof(int));

Comprehensive case analysis: 

4. memset memory setting function

Header file: #include<string.h>

用法:void *memset(void *s, int c, size_t n);

s is the starting address of the space

c is the value filled for each byte in the space

n is the byte width of the space

Case: dynamic array

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
void test()
{	
	int n = 0;
	printf("请输入元素个数:");
	scanf("%d", &n);
	int *p = NULL;
	p=(int *)malloc(n*sizeof(int));
	if (p = NULL)
	{
		return;
	}
	//将申请的堆区空间清0
	memset(p, 0, n * sizeof(int));
	int i=0;
	for ( i = 0; i < n; i++)
	{
		scanf("%d", p + i);
	}
	for ( i = 0; i < n; i++)
	{
		printf("%d ", p[i]);//*(p+i);
	}
	free(p);
	return;
}
int main(int argc, char const* argv[])
{
		test();
		return 0;
}

5. realloc memory increase and decrease function

Re-apply memory         based on the memory pointed to by s , and the size of the new memory is size bytes. If there is enough space
behind the original memory , add it . If the memory behind is not enough , the relloc function will find in the heap A memory request of size bytes , copy the contents of the original memory, then release the original memory, and finally return the address of the new memory .

Header file: #include<stdlib.h>

用法:void *realloc(void *ptr, size_t size);

ptr is the start address of the old space
size is the size of the old space plus the size of the new space
The return value is the start address of the entire space after the increase or decrease of the space

Note: Pointer variables must be used to obtain the return value of realloc, p=realloc(p,20+20);

#include <stdio.h>
#include<stdlib.h>
void test04()
{
int n = 0;
printf("输入int元素的个数:");
scanf("%d", &n);
//根据元素的个数申请空间
int *p = NULL;
p = (int *)calloc(n, sizeof(int));
if (p == NULL)
{
    return;
}
//获取键盘输入
int i = 0;
for (i = 0; i < n; i++)
{
    scanf("%d", p + i);
}
//遍历数组元素
for (i = 0; i < n; i++)
{
    printf("%d ", p[i]); //*(p+i)
}
printf("\n");
printf("输入新增的元素个数:");
int new_n = 0;
scanf("%d", &new_n);
//追加空间
p = (int *)realloc(p, (n + new_n) * sizeof(int));
printf("输入%d个新增元素:", new_n);
//输入新增的元素
for (i = n; i < n + new_n; i++)
{
    scanf("%d", p + i);
}
//遍历数组元素
for (i = 0; i < n + new_n; i++)
{
    printf("%d ", p[i]); //*(p+i)
}
printf("\n");
free(p);
}

3. Memory leak (understand)

        The requested memory, whose first address is lost, can no longer be used or released, and this piece of memory is leaked.

Case 1:

char *p;

p=(char *)malloc(100);

p="hello world";//p points to another place

//After that, the requested 100 bytes cannot be found, and the dynamically requested 100 bytes are leaked.

Case 2:

void test()
{
    char *p;
    p=(char *)malloc(100);
    //函数结束该内存未释放
}
int main()
{
    test();
    test();//调用一次,内存就泄漏一次。
}

 Case 2 solution: use the free function to release the memory or return the pointer variable at the end of the call

The free function releases:

void test()
{
    char *p;
    p=(char *)malloc(100);
    //函数结束该内存未释放
    ...
    free(p);
}
int main()
{
    test();
}

 The pointer variable returns:

void test()
{
    char *p;
    p=(char *)malloc(100);
    //函数结束该内存未释放
    ...
    return p;
}
int main()
{
    char *q;
    q=test();
    /调用一次,内存就泄漏一次。
}

Guess you like

Origin blog.csdn.net/m0_75045191/article/details/131602637