当前位置:网站首页>[C language] the use of dynamic memory development "malloc"

[C language] the use of dynamic memory development "malloc"

2022-07-05 10:00:00 Chenze

write in front  

Hello everyone , I'm Chen Ze , I hope after you read it , It can help you , Insufficient, please correct ! Learn and communicate together
2021 Blog star of the year, Internet of things and embedded development TOP5~2021 Blog star Top100~ Alibaba cloud expert Blogger &  Star Blogger ~ Nuggets ⇿InfoQ Creator ~ Zhou Bang 71﹣ General list 1479
This paper is written by Chen Ze   original CSDN If you need to reprint, please inform
Personal home page ⇲ Beating soy sauce desuCSDN Blog
Welcome to → give the thumbs-up + Collection ️ + Leaving a message. ​
Series column ⇥【C】 series _ Chen Ze's blog -CSDN Blog [₀~¹]
️ We are not on the stage of our choice , Acting is not the script we chose

  Sunflower treasure dian

 write in front  

Static memory development ₀

Dynamic memory development ¹

Stack

Pile up

 malloc() function

free() function

malloc() Dynamic memory development and use  

calloc()

calloc() Dynamic memory development and use   

 realloc()

realloc() Dynamic memory development and use    

Common errors in memory development  

Static memory development ₀

Let's talk about dynamic memory development , Let's first introduce the methods we have learned to open up memory space .

char arr[10] = {0}; // Continuous development on the stack 10 Bytes of memory space 
int a = 1; // Open up on the stack 4 Byte space 

These are the knowledge points we learned earlier, and the common ways to open up memory space ↓

  • The size of the memory space we open up is fixed .
  • When we declare an array , You must specify the length in the array , In this way, the memory space it needs can be known by the compilation system . So as to get an allocation on memory . 

But this leads to a problem , Sometimes, the size of space we need must be known after the program runs , The way to open up space when compiling arrays cannot be satisfied . 

​​ 

This is like I want to input the information of 200 students during the operation of a program , At this point, I use an array to allocate 1000 Information about a classmate . At this time, I will waste a lot of memory space . When I want to enter 2000 When I receive information from my classmates , At this time, the array is allocated 1000 Students' information cannot be stored . 

Then we can use Dynamic memory development You can solve this problem perfectly .


Dynamic memory development ¹

What is dynamic memory development ?

Dynamic memory allocation (Dynamic Memory Allocation) It refers to the method of dynamically allocating or reclaiming storage space to allocate memory during program execution . Dynamic memory allocation does not need to allocate memory space in advance as static memory allocation methods such as array , But by the The system allocates according to the needs of the program , And the allocated size is the size required by the program .

​​

Now that we have reached this point, let's talk about the concept of stack and heap n:↓ This is more convenient and easy to understand .

Stack

When executing a function , The storage units of local variables inside the function can be created on the stack , At the end of function execution, these storage units will be automatically released . The stack area mainly stores the local variables allocated by the running function , The parameters of the function , Return the data , Return address, etc .

Pile up

Variables are usually defined ( Or object ), The compiler can use this variable at compile time ( Or object ) The type of knows the size of the required memory space , Thus, the system allocates certain storage space for them at the appropriate time . This memory allocation is called Static storage allocation ; Some operands can only be determined when the program is running , So you can't reserve storage space for them at compile time , Only when the program is running , The system allocates memory according to the requirements of runtime , This method is called Dynamic storage allocation . All dynamic storage allocations are Heap area In the middle of .

When a program runs to a variable or object that needs to be dynamically allocated , You must apply to the system to get a piece of storage space of the required size in the heap , Used to store the variable or object . When the variable or object is no longer used , At the end of its life , To explicitly free the storage space it occupies , In this way, the system can reallocate the heap space , Reuse limited resources .

Next, I will introduce the use of functions for dynamic memory development , Know how to use it , Then it is equivalent to learning the dynamic memory development .  


 malloc() function

malloc() Declaration of functions , As shown below ↓

void* malloc (size_t size);

Allocate a memory block with a size of bytes , Returns a pointer to the beginning of the block .

The contents of the newly allocated memory block are not initialized , There are still uncertain values .

If size by 0, The return value depends on the specific library implementation ( It may be a null pointer , Maybe not ), But the returned pointer should not be dereferenced . 

size→ Size of memory block , In bytes .

  • Size_t Is an unsigned integer type .

success , Pointer to the memory block allocated by the function .

The type of this pointer is always void*, It can be converted to a data pointer of the desired type , So that it can be dereferenced .

If the function fails to allocate the requested memory block , Then return a null pointer NULL.

Use malloc() The function requires a header file #include<stdlib.h>

free() function

free() Declaration of functions , As shown below ↓

void free (void* ptr);

ptr →  Pointer to a memory block to free memory , The memory block was previously called malloc、calloc or realloc To allocate memory . If the parameter passed is a null pointer , No action will be performed .

This function does not return any value . 

actually free()  Function is specially used to release or reclaim dynamic memory . Be careful :free() In the middle of ptr It points to the space of the stack area , If you store heap space, it is undefined .

When we finish recycling , It's better to ptr The parameter is set to NULL, So it can't find the original space .

Use free() The function requires a header file #include<stdlib.h>

malloc() Dynamic memory development and use  

The sample code is as follows ↓

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
	int* p = (int*)malloc(10 * sizeof(int));
	if (p == NULL)
	{
		perror("main:");//perror() -  Print error messages 
	}
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*(p + i) = i;// Initialize assignment 
		printf("%d\n", p[i]);// Equivalent to array print elements 
	}
	// Reclaim memory space 
	free(p);
	p = NULL;
	return 0;
}

The operation results are as follows ↓

0 1 2 3 4 5 6 7 8 9 

Have you found that the access to arrays is exactly the same , Only one is in The stack area On , This is in Heap area On .

If it is  malloc() The function returns a null pointer n, We just have to take malloc() Just change the memory block space . as follows ↓

int* p = (int*)malloc(1000000000000000 * sizeof(int));

The result of this operation is →Not enough space( There are not enough vacancies ) Is actually memory space .


calloc()

calloc() Declaration of functions , As shown below ↓

void* calloc (size_t num, size_t size);

by num The element array allocates a piece of memory , The size of each element is bytes long , And put all its bits Initialize to zero . The effective result is to assign a (num*size) Zero initialization memory block of bytes .

If size by 0, The return value depends on the specific library implementation ( It may be a null pointer , Maybe not ), But the returned pointer should not be dereferenced . 

  • Parameters

num →  Number of elements to allocate .

size →   The size of each element .

size_t →   It's an unsigned integer .

  • Return value

success , Pointer to the memory block allocated by the function .

The type of this pointer is always void*, It can be converted to a data pointer of the desired type , So that it can be dereferenced .

If the function fails to allocate the requested memory block , Then return a null pointer .

calloc() Functions and malloc() The biggest difference between functions is nothing more than :calloc() Than malloc() There is one more parameter , as well as calloc() The function of will initialize each byte to full 0, and malloc() The contents of each byte will not be initialized .calloc() Each byte of the requested space will be initialized completely before returning the address 0 Of .

calloc() Dynamic memory development and use   

The sample code is as follows ↓

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
	int* p = (int*)calloc(10,sizeof(int));
	if (p == NULL)
	{
		perror("main:");//perror() -  Print error messages 
	}
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		printf("%d\n", p[i]);// Equivalent to array print elements 
	}
	// Reclaim memory space 
	free(p);
	p = NULL;
	return 0;
}

The operation results are as follows ↓ 

0 0 0 0 0 0 0 0 0 0

From here we can find ,calloc() The function helps us initialize to 0 Of . So if we change the code here to malloc() See what happens in the form of function , Other constant operation results of laikangkang .

int* p = (int*)malloc(10 * sizeof(int));

-842150451 → ⑩ That's ok

From here we can know malloc() Function does not help us initialize .


 realloc()

realloc() Declaration of functions , As shown below ↓

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

function → Change by ptr The size of the memory block pointed to . 

  • Parameters

ptr → Is to adjust the memory address .

size → New size of memory block , In bytes . New size after adjustment .

size_t →   It's an unsigned integer .

Return value → A pointer to the reallocated memory block , It can work with ptr identical , It can also be a new location .
The type of this pointer is void*, It can be converted to the required data pointer type , So that it can be dereferenced .

Be careful → If ptr It's a null pointer , The behavior of this function is similar to malloc(), Allocate a new block with a size of bytes , And return a pointer to the beginning of it .  As shown in the following code ↓

int* p = (int*)malloc(10 * sizeof(int));
int* p = (int*)realloc(NULL,10 * sizeof(int));

In fact, it is equivalent to . 

realloc() Dynamic memory development and use    

The sample code is as follows ↓ 

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
	int* p = (int*)malloc(10 * sizeof(int));
	if (p == NULL)
	{
		perror("main:");//perror() -  Print error messages 
	}
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*(p + i) = i;
	}
	// Need here p The pointing space of is larger , increase 20 An integer type .realloc() -  Adjust the space 
	int* ptr = (int*)realloc(p, 20 * sizeof(int));
	if (ptr != NULL)
	{
		p = ptr;
	}
    // Reclaim memory space 
	free(p);
	p = NULL;
	return 0;
}

Check whether realloc() Adjust the p Of memory space . 


Common errors in memory development  

Ⅰ→ Yes NULL Dereference operation of pointer .

Ⅱ → Cross border access to dynamic open space .

Ⅲ → Use free() Free up non dynamic space .

Ⅳ → Use free() Free part of dynamic memory .

Ⅴ → For the same dynamic space , use free() Release many times .

Ⅵ → Forgetting to release the dynamically opened space will lead to memory leakage , It's more serious .

(๐॔˃̶ᗜ˂̶๐॓) Ask for praise, attention and three connections ....................
原网站

版权声明
本文为[Chenze]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050934482110.html