What is a memory leak and how to prevent memory leaks


foreword

The reading volume is very low recently (⁠ ≧⁠Д⁠≦⁠)


What is a memory leak

Memory leak (Memory Leak) refers to that during the running of the program, the allocated memory space is not released or recovered correctly after it is no longer used, which makes this part of the memory no longer available to other programs or the operating system, resulting in a waste of memory resources or insufficient.
When a program runs, it needs to allocate a certain space in memory to store data and temporary variables.
Typically, programs release memory spaces for use by the operating system or other programs when they are no longer needed. However, if there is a memory leak problem in the program, these unused memory spaces will not be released correctly, resulting in continuous increase of memory.

Memory leaks can cause the following problems:

  1. Waste of memory resources: The unreleased memory usage will gradually increase, eventually occupying too much memory resources, resulting in a decline in overall system performance.
  2. System crash or exception: When the memory leak reaches a certain level, the system may crash or have an abnormal error due to insufficient memory.
  3. System performance degradation: memory leaks will lead to waste of resources, slow down the response of the system, and even cause the system to become unstable.

Common causes of memory leaks include incorrectly freeing dynamically allocated memory, circular references, uncleaned caches, etc. Memory leaks can be prevented and fixed by using proper memory management techniques, writing high-quality code, and using memory analysis tools.

example one

#include <stdio.h> 
#include <stdlib.h>    
int main() 
{
    
    
int *p;
p = (int*)malloc(sizeof(int) * 10);
//动态分配10个int类型变量的内存
//如果调用malloc函数失败,p会变成空指针,需要检查p是否为空指针再进行下一步操作
return 0;
}

Explanation:
A memory leak in the code means that malloc()after the function allocates memory, free()the function is not used to release the memory. Since this part of memory is not released, the operating system will not be able to reclaim this part of the unreleased memory space after the program finishes running.
Solution: To solve this problem, you need to use a function to release
the dynamically allocated memory space when it is no longer in use . For example, add to free the pointed-to memory space free()before the program ends .free(p);p

Example two

#include <stdio.h>
#include <stdlib.h>
void memoryLeak()
{
    
    
int *ptr = (int*)malloc(sizeof(int));    // 没有释放动态分配的内存,导致内存泄漏
// 这部分内存无法被其他程序或操作系统使用
}
int main()
{
    
    
memoryLeak();
printf("内存泄漏示例\n");
return 0;
}

Explanation:
In this code, we define a memoryLeak()function called . Inside the function, we use malloc()the function to dynamically allocate a inttype of memory and assign its address to ptrthe pointer. However, before the end of the function, free()the function is not used to release this part of the memory, resulting in a memory leak.
In main()the function, we called memoryLeak()the function and printed a simple message after it. However, due to memory leaks, the freed memory cannot be reclaimed, which may cause the system's memory resources to be wasted, which may eventually lead to system performance degradation or crash.
Solution:
When you no longer need to use the dynamically allocated memory, you should use free()a function to explicitly release the memory, such as memoryLeak()adding free(ptr);a statement at the end of the function. This ensures that memory can be released when it is not in use, avoiding memory leaks.

special edition

#include <stdio.h> 
#include <stdlib.h>
int main()
{
    
    
int *p = (int *)malloc(sizeof(int));
// 申请动态内存
*p = 123;
printf("*p = %d\n", *p);
// 输出 123
free(p);
// 释放内存
printf("*p = %d\n", *p);
// 错误: 程序运行错误(或者段错误)
return 0;
}

The function of this code is to dynamically malloc()allocate a intmemory space of a type size through a function, and assign its address to a pointer variable p. Then, the integer value 123 is stored in that memory space, and printf()the value is printed out by the function.
Next, free()the previously allocated memory space is freed using the function. Finally, with the memory space already freed, try to paccess it using a pointer and print its value. This is wrong behavior because the memory space has been freed and is no longer accessible to the program, thus causing a runtime error or a segmentation fault.
Therefore, the last line of code causes an error in the program. To avoid this error, you should avoid continuing to use a pointer to a freed memory address after freeing the memory.
(If you don’t understand, look here. To put it bluntly, the memory space has been released and the pointer is still being accessed.)
Hazards:

  1. Undefined Behavior: Attempting to access freed memory is undefined behavior. In this case, the statement in the code printf("*p = %d\n", *p);causes the program to malfunction. This may cause the program to crash or produce unpredictable behavior.
  2. Memory leak: Although the code is used free(p)to free memory, it is still trying to access the freed memory space after freeing. This can lead to memory leaks, as freed memory cannot be reclaimed by other programs or the operating system, wasting memory resources.
  3. Security implications: If the leaked memory contains sensitive data, it could lead to security concerns. Other malicious programs or hackers may use the leaked memory to obtain sensitive information, thereby threatening the security of the system.

summary/end

I was going to tell a story but I didn't write a script to update this article

Guess you like

Origin blog.csdn.net/m0_54471074/article/details/131970630