Detailed explanation of the basics of dynamic memory management

Table of contents

1. Why there is dynamic memory allocation

2. Introduction to dynamic memory functions

2.1 malloc and free

Function:

Parameters and return values:

Precautions:

tip:

2.2 calloc

 2.3 realloc function

Function:

Parameters and return values:

Two cases of realloc opening up space

realloc will take the following measures in order

Question: Can the return value of realloc be accepted with the original pointer?

3. Common dynamic memory errors

3.1. Dereference operation on NULL pointer

3.2. Out-of-bounds access to dynamic open space

3.3. Free release of non-dynamically allocated memory

3.4. Use free to release part of a dynamically allocated memory

3.5. Multiple releases of the same dynamic memory

3.6. Dynamically open up memory and forget to release (memory leak) open up space must be released


1. Why there is dynamic memory allocation

The memory development methods we have mastered are:

int a = 0;
char b[10] = {0};

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

  1. The size of the space opened up is fixed.
  2. When an array is declared, the length of the array must be specified, and the memory it needs is allocated at compile time.

But the demand for space is not just the above situation. Sometimes the size of the space we need is known when the program is running .

The way to open up space when compiling the array is not satisfactory.

At this time, only dynamic memory development can be used.

2. Introduction to dynamic memory functions

2.1 malloc and free

C language provides a dynamic memory development function - malloc

Function:

Apply for a continuous available space from the memory, and return a pointer to this space.

Parameters and return values:

The parameter is an unsigned integer in bytes, and the return value is void*, which points to the pointer we opened up this space.

Precautions:
  • If the allocation is successful, a pointer to the allocated space is returned.
  • If the opening fails, a NULL pointer is returned, so the return value of the malloc function must be checked !
  • The type of the return value is void*, so the malloc function does not know the type of the opened space, and the specific use is up to the user to decide.
  • If the parameter size is 0, the behavior of malloc is undefined by the standard.
tip:
  • After malloc applies for the space, it directly returns the starting address of the space without initializing the contents of the space.
  • The memory space requested by malloc is returned to the operating system when the program exits. When the program does not exit, the dynamically angry memory will not be actively released, and it needs to be released with the free function.
  • Whenever the free function releases the space, the pointer has no pointed content. In order to prevent wild pointers, it needs to be set to control (that is, after each use of the free function, it needs to be set to a null pointer )
  • The free function cannot release non-dynamically allocated memory space, this behavior is undefined by the standard
  • If the parameter of the free function is a null pointer, the free function does nothing
int main()
{
	//int arr[10];
	int* p = (int*)malloc(40);
	if (p == NULL)
	{
		perror("malloc");
		return 1;
	}
	//开辟成功
	for (int i=0;i<10;i++)
	{
		printf("%d\n", *(p + 1));
	}
    free(p);
    p=NULL;
	return 0;
}

2.2 calloc

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

  •  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.
  • The only difference from the function malloc is that calloc will initialize each byte of the application to 0 before returning the address

for example:

 2.3 realloc function

Function:

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

Parameters and return values:

ptr is the memory address to be adjusted, size is the new size after adjustment (in bytes), and the return value is the starting position of the memory after adjustment. If ptr is a null pointer, the function of the function is the same as the malloc function.

Two cases of realloc opening up space

1. There is enough space behind the original space

Directly return the starting address of the original space

2. There is not enough space behind the original space

realloc will take the following measures in order

(1) Open up new space

(2), the data in the old space will be copied to the new space

(3), release the old space

(4), return the starting address of the new space

Question: Can the return value of realloc be accepted with the original pointer?

Answer: No, because if realloc fails to increase capacity , it will return a null pointer, and the space pointed to by the original pointer has not been released, so it will be set as a null pointer, which will cause a memory leak ! Therefore, we should use a new pointer to accept it, and then judge whether the capacity increase is successful. If successful, assign the content of the new pointer to the original pointer, otherwise the program ends.

int main()
{
	int* p = (int*)malloc(40);
	if (p == NULL)
	{
		perror(malloc);
		return 1;
	}
	for (int i=0;i<2;i++)
	{
		*p = i + 1;
		p++;
		//p[i]=i+1;
	}
	int* ret = (int*)realloc(p, 80);
	if (ret == NULL)
	{
		perror(realloc);
		return 1;
	}
	p = ret;
	for (int i=0;i<20;i++)
	{
		printf("%d\n", p[i]);
	}
	free(p);
	p = NULL;
	return 0;
}

 The above is the correct way to use realloc to increase capacity. If the capacity is reduced, directly enter a value smaller than the original size.

3. Common dynamic memory errors

3.1. Dereference operation on NULL pointer

Solution: Determine whether the return value of the memory allocation function malloc/calloc/realloc is empty

3.2. Out-of-bounds access to dynamic open space

3.3. Free release of non-dynamically allocated memory

3.4. Use free to release part of a dynamically allocated memory

 Note that p at this time does not point to the starting address of our dynamic open space, but is equivalent to a part of the dynamic memory. At this time, it is wrong to use free to release. Free release should start from the starting address of the dynamic memory !

Do not allow the start pointer to deviate! 

3.5. Multiple releases of the same dynamic memory

3.6. Dynamically open up memory and forget to release (memory leak) open up space must be released

Solution:

The space requested by dynamic memory will not be automatically destroyed when it goes out of scope. There are only two ways to destroy it (return the memory to the operating system): exit the program and the free function.

The malloc and free functions are used in pairs !

Guess you like

Origin blog.csdn.net/hanwangyyds/article/details/131839879