当前位置:网站首页>Explain C language dynamic memory management in detail

Explain C language dynamic memory management in detail

2022-07-19 14:31:00 Finally - null

Make a little progress every day , Persistence makes a big difference !!!

Preface :

stay C In the process of language learning, for the storage of variables in memory, you first need to apply for space from memory , Sometimes we can't decide how much space to apply for at one time , This requires us to use memory more flexibly , When there is not enough memory to apply for at the beginning, you can continue to apply for space on the original basis

1. The introduction of dynamic memory function :

1.malloc

#include<stdlib.h>

void* malloc (size_t size);

Apply to this function for memory One piece continuously available Space , And return the pointer to this space .

The rules for using functions :

If the development is successful , Then return a pointer to open a good space ;

If the development fails , Returns a NULL The pointer ;

The return value is void*, Therefore, it is necessary to use type forced conversion according to the actual situation ;

If size The value of is 0, Then the standard is undefined , Depends on the compiler .

2.free

void free (void* ptr);

Used for dynamic memory release and recycling

The rules for using functions :

If parameters ptr The pointed space is not opened dynamically , that free The behavior of a function is undefined

If ptr yes NULL The pointer , Then the function does nothing

3.calloc

void* calloc (size_t num, size_t size);

The rules for using functions :

by num Size is size The elements of open up a continuous space , And put the space Each byte is initialized to 0;

And malloc The function is different in that it initializes each byte of the requested space as 0, Everything else is the same

4.realloc

void* realloc (void* ptr, size_t size);

You can flexibly adjust the memory size

Function usage rules :

ptr Is to adjust the starting position of memory ;

szie Is the adjusted total size ;

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

realloc There are two ways to adjust memory :

situation 1: Continue to add space to the original space , The original spatial data does not change

situation 2: When you continue to add space to the original space , There is not enough space for follow-up , So I will find a new space in memory , And will put the original data copy into the newly applied space . 

 

2. Common dynamic memory errors :
 

1. Yes NULL Pointer to dereference :

int* p = (int*)malloc(8000);
	*p = 20;
	free(p);
	p = NULL;

2. Cross border access to dynamically opened memory :

int* p = (int*)malloc(40);
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
	}
	int i = 0;
	for (i = 0; i <= 10; i++)
	{
		*(p + i) = i;
	}
	for (i = 0; i <= 10; i++)
	{
		printf("%d ", *(p + i));
	}
	free(p);
	p = NULL;

3. For non dynamically opened memory free Release :

int a = 10;
	int* p = &a;
	free(p);
	p = NULL;

4. Use free Release part of the space opened dynamically :
 


	int* p = (int*)malloc(40);
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
	}
	int i = 0;
	for (i = 0; i < 5; i++)
	{
		*p = i;
		p++;
	}
	free(p);
	p = NULL;

5. Release the same dynamic memory multiple times :

    int* p = (int*)malloc(50);
	free(p);
	//……

	free(p);

6. Dynamic development of memory forget to release ( Memory leak ):

void test()
{
	int* p = (int*)malloc(40);
	if (p != NULL)
	{
		*p = 10;
	}

}
int main()
{
	test();
	return 0;
}

test After the function is called , The function stack frame is returned to the operating system , however p The dynamic development memory originally pointed to has not been released .

3. Classic written test questions about dynamically opening up memory :
 

1. Topic 1 :

test What will be the result of function operation ?

void GetMemory(char*p)
{
	p= (char*)malloc(100);
}
void test (void)
{
	char* str = NULL;
	GetMemory(str);
	strcpy(str, "hello world");
	printf(str);
}
int main()
{
	test();
	return 0;
}

  modify :

2. Topic two :

char* GetMemory(void)
{
	char p[] = "hello world";
	return p;
}
void test(void)
{
	char* str = NULL;
	str = GetMemory();
	printf(str);
}
int main()
{
	test();
	return 0;
}

 

3. Topic three :
 

void GetMemory(char**p, int num)
{
    *p	= (char*)malloc(num);
}
void test(void)
{
	char* str = NULL;
	GetMemory(&str, 100);
	strcpy(str, "hello");
	printf(str);
}
int main()
{
	test();
	return 0;
}

modify :

 

4. Topic four :

void test(void)
{
	char* str = (char*)malloc(100);
	strcpy(str, "hello");
	free(str);
	if(str!=NULL)
	{
		strcpy(str, "world");
		printf(str);
	}
}
int main()
{
	test();
	return 0;
}

modify :

 

4. Flexible array :

1. Concept :

The last element in the structure can be an array of unknown size , This is called a flexible array .

 

2. The characteristics of flexible arrays :

1. The flexible array member in the structure is preceded by at least one other member ;

2.sizeof The returned structure size does not include the size of the flexible array ;

3. The structure containing the members of a flexible array is malloc Function to dynamically allocate memory  , And the allocated size should be larger than the total size of the structure , Adapted to the size of the flexible array ;

 

3. Advantages of flexible arrays :

The above structure can also be designed as the following code :

 

 

Compare the advantages of flexible arrays with each other :

1. Facilitate the release of memory :
The flexible array only needs to be released once to release memory , It greatly reduces the problem of forgetting to release dynamic memory

2. Conducive to access speed :

It is beneficial to improve the access speed , It also helps reduce memory fragmentation

summary :

So that's about C Detailed explanation of knowledge points of language dynamic memory development , I hope I can help each other in the process of learning , Promote each other , Welcome to like , Leave a comment !!!

原网站

版权声明
本文为[Finally - null]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207172120235314.html