C language - dynamic memory management (dynamic memory function)

foreword

This issue is divided into three articles to introduce related content of dynamic memory management. Follow bloggers to learn more
Blogger blog link: https://blog.csdn.net/m0_74014525
This issue introduces dynamic memory functions, how to use functions, function formats, in Use in the required attention points and the memory allocation area of ​​​​the C/C++ program


series of articles

Part 1: C Language - Dynamic Memory Management (Dynamic Memory Functions)
Part 2: C Language - Common Dynamic Memory Errors
Part 3: C Language - Flexible Arrays


1. What is dynamic memory allocation

Dynamic memory allocation means that during the running of the program, the program itself requests the operating system to allocate a certain amount of memory space to store the data required for the running of the program. Since the dynamically allocated memory space is variable during program execution, it is more flexible than static allocation.

The advantage of dynamic memory allocation is that the memory size can be dynamically adjusted according to actual needs, thereby avoiding wasting memory. However, if the programmer manages the dynamically allocated memory carelessly, it may cause problems such as memory leaks or memory overflows, seriously affecting the performance and stability of the program. Therefore, you need to pay attention to the release and management of memory when using dynamic memory allocation.

Common dynamic memory allocation functions include malloc, calloc, reallocand so on. Among them, malloc allocates a memory block of a specified size, calloc allocates and initializes a certain number of memory blocks, and realloc can readjust the size of an allocated memory block.

Second, why there is dynamic memory allocation

The memory development methods we have mastered are:

int val = 20;//在栈空间上开辟四个字节
char arr[10] = {
    
    0};//在栈空间上开辟10个字节的连续空间

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

  1. The space allocation size is fixed.
  2. When the 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 can only be known when the program is running, and
the way to open up space when the array is compiled cannot be satisfied.
At this time, you can only try dynamic storage and development.

3. Introduction of dynamic memory functions


1. malloc

mallocThe function is used in the C language to apply for a memory space of a specified size from the memory when the program is running.

Function format:

void* malloc (size_t size);

Among them, size_t is an unsigned integer type, which is used to represent the number of bytes to apply for memory. The malloc function returns a void pointer that points to the starting address of the allocated memory space. If the allocation fails, the malloc function returns a null pointer NULL.

Function features:

  • 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 malloc 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 user can decide by himself when using it.
  • If the parameter size is 0, the behavior of malloc is undefined by the standard and depends on the compiler.

When using the malloc function to apply for memory, you need to pay attention to the following points:

1. The requested memory size should be the number of bytes of the variable or data type multiplied by the number of elements to be stored or manipulated to ensure that sufficient memory space is applied.
2. The requested memory space must be released using the free function, otherwise memory leaks will result.
3. The requested memory space will not be automatically initialized, that is, the data in it is random and needs to be initialized manually.

Example demonstration:

#include <stdio.h>
#include <stdlib.h>

int main() {
    
    
    int *p;
    p = (int*)malloc(10*sizeof(int)); //申请10个int类型数据的内存空间
    if (p == NULL) {
    
     //判断申请是否成功
        printf("Memory allocation failed.");
        exit(1);
    }
    for (int i = 0; i < 10; i++) {
    
     //手动初始化数据
        *(p+i) = i;
    }
    for (int i = 0; i < 10; i++) {
    
     //输出数据
        printf("%d\t", *(p+i));
    }
    free(p); //释放内存空间
    p=NULL;  //将指针置为空
    return 0;
}
 

2. free

freeA function is a function used in the C language to release dynamically allocated memory

Function format:

void free (void* ptr);

Among them, ptr is the pointer returned by the previous call to malloc, calloc or realloc function. After calling the free function, the memory pointed to by the pointer will be reclaimed by the operating system and can be allocated to other programs again.
Function features:

  • If the space pointed to by the parameter ptr is not dynamically opened, the behavior of the free function is undefined.
  • If the parameter ptr is a NULL pointer, the function does nothing.

When using the free function, you need to pay attention to the following points:

1. Only dynamically allocated memory can be freed, not memory in the stack or global variables.
2. If the same pointer is freed multiple times, it will cause a program exception.
3. If the pointer is NULL, no operation is performed.

3. calloc

callocThe function is a memory allocation function in the C language, which is used to allocate a continuous space of a specified size in the memory, and initialize each byte in it to 0.
Function format:

void* calloc (size_t num, size_t size);

Among them, num represents the number of elements to be allocated, and size represents the size of each element. The function returns a pointer to the newly allocated memory, or NULL if the allocation failed.
Function features:

  • The only difference from the function malloc is that calloc will initialize each byte of the requested space to all 0s before returning the address.
  • Unlike the malloc function, the calloc function will automatically clear the allocated memory space when allocating memory, so it is generally used when memory needs to be initialized. But its disadvantage is that it is slower than the malloc function, because it needs to be cleared when allocating memory.

When using the calloc function to apply for memory, you need to pay attention to the following points:

1. The requested memory size should be the number of bytes of the variable or data type multiplied by the number of elements to be stored or manipulated to ensure that sufficient memory space is applied.
2. The requested memory space must be released using the free function, otherwise memory leaks will result.
3. The requested memory space will not be automatically initialized, that is, the data in it is random and needs to be initialized manually.
4. Different from malloc, calloc will initialize each byte of the requested space to all 0s before returning the address.

Example demonstration:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    
    
	int* p = (int*)calloc(10, sizeof(int));
	if (NULL != p)
	{
    
    
		//使用空间
	}
	free(p);
	p = NULL;
	return 0;
}

insert image description here
如何对申请的内存空间的内容要求初始化,那么可以很方便的使用calloc函数来完成任务


4. realloc

reallocfunction is a library function in C language, which is used to reallocate dynamically allocated memory space.
1. Used to adjust the size of an existing memory block,
2. Allocate a new memory block
3. Used to release an existing memory block when passing it a null pointer.

Function format:

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

ptr represents a pointer to a block of memory that has been dynamically allocated.
size represents the new size of the memory block that needs to be reallocated.
Return value: If the allocation fails, a NULL pointer is returned; otherwise, a new pointer is returned, pointing to the reallocated memory block.

Function features:

When using the realloc function to apply for memory, you need to pay attention to the following points:

1. If the new size is larger than the old size, the realloc function will allocate additional memory behind the original memory block to make it the new size.
2. If the new size is smaller than the old size, the realloc function will free some memory to make it the new size.
3. If ptr is a null pointer, it is equivalent to calling the malloc function. If size is 0, it is equivalent to calling the free function.

There are two situations when realloc adjusts the memory space:

  • Case 1: There is enough space after the original space
  • Case 2: There is not enough space after the original space
    insert image description here

Case 1:
When it is case 1, if you want to expand the memory, you can directly add space after the original memory, and the data in the original space will not change.

Case 2:
In case 2, if there is not enough space after the original space,
the expansion method is: find another continuous space of suitable size on the heap space to use. This function returns a new memory address.
Due to the above two situations, some attention should be paid to the use of the realloc function.

4. Memory development of C/C++ programs

insert image description here

1. Memory allocation area

Several areas of C/C++ program memory allocation:

Stack area (stack) When a function is executed, the storage units of local variables in the function can be created on the stack, and these storage units are automatically released when the function execution ends. The stack memory allocation operation is built into the instruction set of the processor, which is very efficient, but the allocated memory capacity is limited. The stack area mainly stores local variables allocated by running functions, function parameters, return data, return address, etc.
Heap area (heap) Generally, it is allocated and released by the programmer. If the programmer does not release it, it may be recovered by the OS at the end of the program. The allocation method is similar to a linked list.
Data segment (static area) (static) Store global variables and static data. Released by the system after the program ends.
code snippet Store the binary code of the function body (class member functions and global functions).

Summarize

An overview of the important points of this blog:
mallocFunction: used for dynamic memory development
callocfunction: also used for dynamic memory development, different from malloc, calloc function will initialize each byte to 0
reallocfunction: used to expand memory space, you need to pay attention Increase the return of memory, divided into case 1 and 2
freefunctions: used to release dynamic memory space


如这篇博客对大家有帮助的话,希望 三连 支持一下 !!! 如果有错误感谢大佬的斧正 如有 其他见解发到评论区,一起学习 一起进步。

Guess you like

Origin blog.csdn.net/m0_74014525/article/details/131789605