内存泄漏(Memory Leak)是由于内存分配错误导致计算机程序中的资源错位。当未使用的RAM位置仍未释放时,就会发生这种情况。不要将内存泄漏与空间泄漏相混淆,空间泄漏是指程序使用的RAM超出了必要的数量。Windows 11/10/8/7系统上发生内存泄漏时,尽管内存未在使用,但仍无法访问。
Windows 11/10 中的内存泄漏
在开始之前,您应该知道内存(Memory)泄漏是一个需要调试的软件问题——例如在Java、JavaScript、C/C++、Windows等中。不需要物理更换RAM或硬盘。
为什么不好
很明显,内存泄漏是不好的,因为它是一个错误,是系统中的一个缺陷。但是让我们看看它究竟是如何影响系统的:
- 由于即使不使用内存也不会释放内存,因此会导致内存耗尽。
- 内存耗尽会导致软件老化。
- 可用内存减少会导致响应时间增加和系统性能下降。
- 未经检查的内存泄漏最终会导致应用程序崩溃。
为了识别内存泄漏,程序员需要访问程序的源代码。
定位泄漏
为了解决一个问题,我们首先需要识别它。定位内存泄漏的基本步骤是:
- Affirmation:确定是否发生泄漏。
- 查找内核模式内存泄漏(Finding Kernel-mode memory leak):定位由内核模式驱动程序组件引起的泄漏。
- 查找用户模式内存泄漏(Finding User-mode memory leak):定位由用户模式驱动程序或应用程序引起的泄漏。
内存分配
应用程序分配RAM(RAM)有不同的模式。如果使用后没有释放空间,无论分配模式如何,都会发生内存泄漏。一些常见的分配模式是:
- HealAlloc函数用于堆内存分配。C/C++ 运行时等效项是 malloc 和 new。
- 用于从操作系统直接分配的VirtualAlloc(VirtualAlloc)函数。
- Kernel32 API(Kernel32 APIs)用于保存应用程序的内核内存。例如(Example),创建文件(CreateFile)、创建线程(CreateThread)。
- User32 API 和 Gdi32 API。
防止 Windows 中的内存泄漏
我们都知道预防胜于治疗,所以这里有一些防止内存泄漏的方法。
监控习惯
您需要留意个别程序和应用程序的异常RAM使用情况。您可以通过按CTRL+SHIFT+ESC进入Windows 任务管理器(Windows Task Manager)并添加Handles、User Objects、GDI Objects等列。
这将帮助您轻松监控资源使用情况。
阅读(Read):计算机中的内存类型有哪些?(What are the Types of Memory in a computer?)
(Microsoft)用于诊断内存泄漏的Microsoft工具
各种工具诊断各种分配模式的内存泄漏:
- 应用程序验证程序(Application Verifier)诊断堆泄漏。
- UMDH(Windows 调试工具(Windows Debugging Tools)的一个组件)通过监视堆内存分配来诊断各个进程的泄漏。
- Trace Capture可全面分析RAM使用情况。
- Xperf 也跟踪堆分配模式。
- CRT Debug Heap不仅跟踪堆分配,而且使编码实践能够最大限度地减少泄漏。
- JavaScript Memory Leak Detector调试代码中的内存泄漏。
使用技巧
- 对Win32(Win32)资源和堆分配使用内核HANDLE和其他智能指针。
- (Get)从ATL(ATL)库获取用于内核分配的自动资源管理的类。C++ 标准具有用于堆分配的auto_ptr 。
- (Encapsulate COM)借助_com_ptr_t或_bstr_t或_variant_t将(_variant_t)COM 接口指针封装在“智能指针”中。
- 监控(Monitor).NET代码是否存在异常内存使用情况。
- 避免(Avoid)函数有多个退出路径,以便在函数结束时从大多数块中的变量中释放分配。
- (Use)仅在释放_finally块中的所有分配后才使用本机异常。将所有堆和句柄分配包装(Wrap)到智能指针中,以便使用 C++ 异常。
- 在重新初始化或丢弃PROPVARIANT对象之前,始终调用PropVariantClear函数。(PropVariantClear)
解决(Troubleshoot)Windows中的内存泄漏问题
就像防止内存泄漏的各种方法一样,阻止内存泄漏的方法也多种多样。但在开始之前,请记住先创建一个系统还原点。
1]关闭进程并重新启动。
如果您发现一个不必要的进程占用了过多的RAM ,您可以在(RAM)任务管理器(Task Manager)中结束该进程。您将需要重新启动设备,以便释放的空间可供其他进程使用。没有重新启动(Restart)内存泄漏问题将无法解决。Runtime Broker是一个存在导致 PC 速度变慢的错误的特定进程。如果单独禁用它,请尝试。
2]内存诊断工具
要访问适用于 Windows的内置内存诊断工具:(Memory Diagnostic Tool)
- 保存所有重要的工作。
- 按Win + R打开运行(Run)窗口。
- 在“运行”(Run)窗口中键入命令mdsched.exe 。
- 重新启动电脑。
- 重新启动后,执行基本扫描或选择“高级(Advanced)”选项,如“测试混合(Test mix)”或“通过计数(Pass count)”。
- 按F10开始测试。
这些仍然是临时修复。
3]检查驱动程序更新
过时的驱动程序会导致内存泄漏。保持所有驱动程序更新:
- 按Win + R并打开运行(Run)窗口。键入devmgmt.msc并按Enter。它将带您进入设备管理器(Device Manager)。
- 检查(Check)过时的驱动程序并全部更新。
- 对于您可能错过的更新,请查看Windows 更新(Windows Update)。
这很简单。
4]优化性能
调整 Windows 的性能将管理包括处理器调度和内存使用在内的一切,以阻止内存泄漏。跟着这些步骤:
- 右键单击“这台电脑(This PC)”,然后在左侧窗格中选择“高级”设置。(Advanced)
- 在“高级(Advanced)”选项卡下,转到“性能(Performance)”,然后转到“设置(Settings)”。
- 选中“调整以获得最佳性能(Adjust for best performance)”并单击“确定(OK)” 。
- 重新启动(Restart)并检查问题是否已解决。
如果这个简单的解决方案不起作用,请尝试下一个解决方案。
5]禁用启动(Startup)时运行的程序(Programs)
禁用麻烦的程序是摆脱内存泄漏问题的唯一方法。转到任务管理器(Task Manager)并禁用故障排除程序。如果您不知道哪些程序会造成问题,请执行以下操作:
- 转到“任务管理器(Task Manager)”。
- 转到“启动(Startup)”。
- 禁用(Disable the startup programs)默认情况下不需要运行的启动程序。
6]对硬盘进行碎片整理
尽管Windows 10会自动为您执行此操作,但您可能需要偶尔对硬盘进行碎片整理以优化性能:
- 转到“这台电脑(This PC)”或“我的电脑(My Computer)”。
- 右键单击(Right-Click)系统硬盘驱动器(通常是 C: 驱动器)。
- 转到“属性(Properties)”下的“工具(Tools)” ,然后选择“优化(Optimize)”。
- 选择要进行碎片整理的驱动器并选择“分析(Analyze)”。
新碎片后重新启动计算机。
7]关闭时清除页面文件
现在它变得越来越复杂了——但不要担心。以下是每次关机时清除页面文件的(clear the Page File at every shutdown)方法:
- 在Search上键入regedit以启动注册表编辑器(Registry Editor)。
- 输入此路径:
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerMemory Management
- 将ClearPageFileAtShutDown( ClearPageFileAtShutDown to ‘1’.)的值更改为“1”。
- 保存更改并重新启动(Restart)设备。
这个应该可以的。请记住,您的关机过程将需要更多时间。
9]禁用Superfetch
此Windows 服务(Windows Service)通过最小化启动时间来优化性能。它允许Windows管理RAM使用情况。禁用Superfetch后的(Superfetch)生活(Life)并不方便,但如果必须,请这样做。至少单独尝试一下以隔离问题:
- 搜索services.msc并转到服务管理器。
- 查找“ Superfetch ”并右键单击它以转到“ Properties ”。
- 选择“停止(Stop)”。
- 还可以从下拉菜单中“禁用”该服务。(Disable)
- 重新启动 PC 并检查性能是否有所改善。
如果这不起作用,请启用 Superfetch。
10]检查恶意软件
使用第三方防病毒软件或 Windows 10 的内部Windows Defender扫描和消除恶意软件。确保(Make)更新防病毒软件以支持您的操作系统,以免它最终成为内存泄漏的原因。
您可能需要查找或防止内存泄漏的每个解决方案都在这里。您可以在MSDN(MSDN)和Microsoft上阅读有关内存泄漏的更多信息。
Find and fix Memory Leaks in Windows 11/10
A Memory Leak is a misplacement of resources in a computer program due to faulty memory allocation. It happens when a RAM location not in use remains unreleased. A memory leak is not to be confused with a space leak, which refers to a program using more RAM than necessary. A memory leak on a Windows 11/10/8/7 system is said to have taken place when the memory is just not accessible despite not being in use.
Memory Leaks in Windows 11/10
Before you begin, you should know that a Memory leak is a software issue to debug – for example in Java, JavaScript, C/C++, Windows, etc. Physically replacing RAM or hard disk isn’t required.
Why is it bad
It is obvious a memory leak is bad because it is a bug, a flaw in the system. But let’s find out how exactly it affects the system:
- Since the memory is not freed even when not in use, it results in memory depletion.
- Exhaustion of the memory results in software aging.
- Reduced available memory leads to increased response time and poor performance by the system.
- An unchecked memory leak can eventually lead to the crash of an application.
In order to identify a memory leak, a programmer needs to have access to the source code of the program.
Locating the leak
In order to solve a problem, we need to identify it first. The basic steps to locate a memory leak are:
- Affirmation: Determining whether a leak has occurred.
- Finding Kernel-mode memory leak: Locating a leak caused by a kernel-mode driver component.
- Finding User-mode memory leak: Locating a leak caused by a user-mode driver or app.
Memory allocation
There are different modes in which applications allocate RAM. If space is not freed after use, the memory leak will occur irrespective of the mode of allocation. Some common allocation patterns are:
- HealAlloc function for heap memory allocation. The C/C++ runtime equivalents are malloc and new.
- VirtualAlloc function for direct allocation from OS.
- Kernel32 APIs to hold kernel memory for the app. Example, CreateFile, CreateThread.
- User32 APIs and Gdi32 APIs.
Prevent memory leaks in Windows
We all know prevention is better than cure so here are some ways to prevent a memory leak.
Monitoring habits
You need to keep an eye out for abnormal RAM usage by individual programs and applications. You can go to the Windows Task Manager by pressing CTRL+SHIFT+ESC and add the columns like Handles, User Objects, GDI Objects, etc.
This will help you easily monitor resource usage.
Read: What are the Types of Memory in a computer?
Microsoft tools to diagnose memory leaks
Various tools diagnose memory leaks for various allocation modes:
- Application Verifier diagnoses heap leaks.
- UMDH ( a component of Windows Debugging Tools) diagnoses leaks for individual processes by monitoring heap memory allocations.
- Trace Capture for a thorough analysis of RAM usage.
- Xperf too tracks heap allocation patterns.
- CRT Debug Heap not only tracks heap allocations but also enables coding practices to minimize leaks.
- JavaScript Memory Leak Detector debugs memory leaks in codes.
Usage Tips
- Use kernel HANDLEs and other smart pointers for Win32 resources and heap allocations.
- Get classes for automatic resource management for kernel allocations from the ATL library. C++ standard has auto_ptr for heap allocations.
- Encapsulate COM interface pointers within “smart pointers” with the help of _com_ptr_t or _bstr_t or _variant_t.
- Monitor the .NET code for abnormal memory usage.
- Avoid multiple exit paths for functions to let allocations be freed from variables in most blocks by the end of a function.
- Use native exceptions only after freeing all allocations in the _finally block. Wrap all heap and handle allocations into smart pointers in order to use C++ exceptions.
- Always call the PropVariantClear function before reinitializing or discarding a PROPVARIANT object.
Troubleshoot memory leaks in Windows
Just like the various ways to prevent memory leaks, there are various ways to stop memory leaks. But before you begin, remember to create a system restore point first.
1] Close processes and restart.
If you see an unnecessary process is taking up too much RAM, you can end the process in the Task Manager. You will need to restart the device so that the freed space is available for use by other processes. Without a Restart memory leak issue won’t be solved. One particular process that has bugs to slow down the PC is Runtime Broker. Try if disabling that alone works.
2] Memory Diagnostic Tools
To access the inbuilt Memory Diagnostic Tool for Windows:
- Save all your important work.
- Press Win + R to open the Run window.
- Type the command mdsched.exe in the Run window.
- Restart the PC.
- After a restart, perform a basic scan or go for the ‘Advanced’ options like ‘Test mix’ or ‘Pass count’.
- Press F10 to start the test.
These are still temporary fixes.
3] Check for Driver updates
Outdated drivers cause memory leaks. Keep all drivers updated:
- Press Win + R and open the Run window. Type devmgmt.msc and press Enter. It will take you to the Device Manager.
- Check for outdated drivers and update them all.
- For updates, you might have missed, check in Windows Update.
This was simple.
4] Optimize performance
Adjusting Windows for performance will manage everything including processor scheduling and memory usage to stop memory leaks. Follow these steps:
- Right-click on ‘This PC’ and select ‘Advanced’ settings on the left pane.
- Under the ‘Advanced’ tab, go to ‘Performance’, followed by ‘Settings’.
- Check ‘Adjust for best performance’ and click OK.
- Restart and check if the issue is solved.
If this simple solution did not work, try the next solution.
5] Disable Programs running on Startup
Disabling the troublesome programs is the only way to get rid of the memory leak issue. Go to Task Manager and disable the troublemaking program. If you don’t know which programs are creating the trouble, do this:
- Go to ‘Task Manager’.
- Go to ‘Startup’.
- Disable the startup programs you don’t need to run by default.
6] Defrag Hard Drive
Although Windows 10 does this for you automatically, you may need to do defrag the hard drives occasionally to optimize performance:
- Go to ‘This PC’ or ‘My Computer’.
- Right-Click the system hard drive (usually C: drive).
- Go to ‘Tools‘ under ‘Properties‘ and select ‘Optimize’.
- Select the drive to defrag and select ‘Analyze’.
Restart your computer after the new fragmentation.
7] ClearPage File at shutdown
It is getting complex now – but don’t worry. Here’s how to clear the Page File at every shutdown:
- Type regedit on Search to launch the Registry Editor.
- Enter this path:
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerMemory Management
- Change the value of ClearPageFileAtShutDown to ‘1’.
- Save the changes and Restart the device.
This ought to do it. Do remember that your shutdown process will take a little more time.
9] Disable Superfetch
This Windows Service optimizes performance by minimizing boot time. It lets Windows manage RAM usage. Life after disabling Superfetch is not convenient but do it if you must. At least try this alone to isolate the problem:
- Search services.msc and go to Services Manager.
- Look for ‘Superfetch’ and right-click it to go to ‘Properties’.
- Select ‘Stop’.
- Also ‘Disable’ the service from the drop-down menu.
- Restart the PC and check if the performance has improved.
Enable Superfetch if this one didn’t work.
10] Check for malware
Use a third-party antivirus software or Windows 10’s in-house Windows Defender to scan and eliminate malware. Make sure the antivirus is updated to support your OS so that it doesn’t end up becoming the reason for the memory leak.
Every solution you might ever need to find or prevent memory leaks is right here. You can read more about memory leaks on MSDN and Microsoft.