Ubuntu 20.04 on WSL2 with Windows 11: Heap Errors Preventing Reboot

Abstract: Resolve heap exhaustion errors in Ubuntu 20.04 on WSL2 with Windows 11 that freeze the system and prevent normal reboot by configuring memory limits or forcing process termination.

Created: 2026-10-06 by
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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More