Heap exhaustion errors in Ubuntu 20.04 on WSL2 with Windows 11 occur when the virtual machine exceeds its allocated memory, freezing the system and preventing a normal reboot. To resolve this, you must manually configure memory limits via the
.wslconfig file or terminate hung processes using PowerShell commands to regain control of the environment.
Understanding the Memory Exhaustion Issue
WSL2 runs Ubuntu as a lightweight Linux kernel inside a Hyper-V virtual machine. By default, WSL2 dynamically allocates memory from your host machine, potentially consuming up to 50% of your total physical RAM or 8 GB, whichever is greater. When running memory-intensive tasks such as compiling large codebases, running Docker containers, or processing big datasets, the Ubuntu instance can exhaust these resources. This leads to heap allocation failures where the Linux kernel cannot allocate more memory for processes.
The symptom is often a complete freeze of the WSL2 instance. You may see errors like "Cannot allocate memory" in terminal outputs, or the system may become unresponsive entirely. Because the underlying VM is stuck in a high-memory state, standard shutdown commands fail, and even restarting the WSL service might not work if the process is deadlocked. This creates a situation where you cannot log out of Ubuntu normally, requiring intervention from the Windows side.
Configuring .wslconfig to Limit Memory
The most effective long-term solution is to cap the maximum memory WSL2 can use. This prevents the virtual machine from starving the Windows host or hitting internal limits that cause crashes. You achieve this by creating a configuration file in your Windows user directory.
Open File Explorer and navigate to
C:\Users\<YourUsername>. Create a new text file named
.wslconfig (note the leading dot). Open this file in a text editor like Notepad and add the following content:
[wsl2]
memory=4GB
swap=0
localhostForwarding=true
In this example,
memory=4GB sets the hard limit for RAM usage. Adjust this value based on your available system resources; leaving some headroom for Windows itself is crucial. Setting
swap=0 disables swap space, which can sometimes help prevent certain disk I/O bottlenecks associated with heavy swapping, though you can set it to a specific size like
swap=2GB if you need swap functionality. After saving the file, you must restart WSL2 completely for changes to take effect. Open PowerShell or Command Prompt and run:
wsl --shutdown
Once WSL2 shuts down, start it again by launching your Ubuntu distribution. The memory limit will now be enforced, preventing future heap exhaustion errors under moderate loads. For more details on managing memory and processor swap settings, see
Managing Memory and Processor Swap in WSL2 with Docker Desktop on Ubuntu.
Forcing a Reboot via PowerShell
If your system is already frozen and you cannot reboot normally, you need to force kill the WSL2 processes from Windows. Since the Ubuntu shell is unresponsive, you cannot use
sudo reboot or
shutdown within the Linux terminal. Instead, use Windows PowerShell with administrative privileges.
Run the following command to list all running WSL2 instances and their associated Virtual Machine IDs:
wsl -l -v
Look for the status of your Ubuntu 20.04 instance. It likely shows as "Running" but is unresponsive. To terminate it immediately, use the shutdown command with the
--all flag or target the specific distribution:
wsl --shutdown
This command sends a termination signal to all WSL2 distributions. If the process is truly deadlocked and does not respond to
wsl --shutdown, you may need to identify the Hyper-V virtual machine directly. Use PowerShell to find the VM name associated with WSL2:
Get-VM | Where-Object Name -like "*WSL*"
Then, stop the VM forcefully:
Stop-VM -Name -TurnOff
Replace
<VM_Name> with the actual name returned by the previous command. This forces the hypervisor to cut power to the virtual machine, clearing the stuck state. Afterward, you can restart WSL2 normally. Note that any unsaved work in open editors within Ubuntu will be lost during this forced shutdown.
Detecting Memory Leaks in Applications
Preventing recurrence involves identifying which applications are causing the heap errors. Common culprits include Node.js processes with infinite loops, Python scripts consuming excessive RAM, or misconfigured Docker containers that do not respect resource limits. Inside Ubuntu, you can monitor memory usage in real-time using tools like
htop or
free -m.
Install
htop if it is not already present:
sudo apt update && sudo apt install htop
Run
htop to view a visual representation of process memory consumption. Look for processes with high RSS (Resident Set Size) values. If you find a specific application consistently spiking memory, consider optimizing its configuration or limiting its resources using cgroups or Docker's
--memory flag. For users encountering broader compatibility issues between different Ubuntu versions in WSL, understanding the differences between releases can also aid in troubleshooting stability issues, as discussed in
Difference between Windows WSL.
Frequently Asked Questions
Why does WSL2 consume so much memory?
WSL2 uses dynamic memory allocation, meaning it grows its footprint as needed up to a default ceiling. This design allows efficient use of resources but can lead to exhaustion if background processes accumulate memory without releasing it. Configuring a static limit in
.wslconfig resolves this unpredictability.
Can I increase the memory limit beyond my physical RAM?
No, the
memory setting in
.wslconfig cannot exceed the total physical RAM installed on your Windows host machine. Attempting to set a value higher than available hardware will result in an error when starting WSL2. You must ensure the limit is lower than your total system memory minus what Windows requires for stable operation.
What happens to my data when I force shut down WSL2?
Forcefully shutting down WSL2 via PowerShell or Task Manager does not automatically save unsaved files in editors like VS Code or Vim. Any changes made since the last save will be lost. Always ensure critical work is saved before performing a forced shutdown or reboot.
Does disabling swap affect performance?
Disabling swap (
swap=0) can improve performance by avoiding disk I/O penalties when memory is tight, but it increases the risk of immediate OOM (Out of Memory) kills if applications spike suddenly. Enabling a small swap file provides a buffer against sudden spikes at the cost of potential slowness during heavy swapping periods.
How do I check if my .wslconfig changes took effect?
After editing
.wslconfig and running
wsl --shutdown, launch your Ubuntu instance and check the memory limits using the command
cat /proc/meminfo. Look for the
MemTotal line, which should reflect the limit you set in the configuration file rather than the default dynamic allocation.