Finding and Fixing Ghostty's Largest Memory Leak
4 months ago
- #memory-leak
- #terminal-emulator
- #debugging
- Ghostty was consuming absurd amounts of memory, with reports of up to 37 GB after 10 days of uptime.
- The memory leak was present since Ghostty 1.0 but became noticeable with the rise of CLI applications like Claude Code.
- Ghostty uses a PageList data structure for terminal memory management, with standard and non-standard pages allocated via mmap.
- A scrollback pruning optimization reused the oldest page as the newest without properly resizing non-standard pages, leading to memory leaks.
- The fix involves never reusing non-standard pages during scrollback pruning, ensuring proper memory deallocation.
- Virtual memory tags on macOS were added to help identify and debug memory allocations related to the PageList.
- Ghostty employs various leak detection methods, including debug builds, unit tests, CI runs with valgrind, and macOS Instruments.
- The community's detailed diagnostics and reproduction efforts were crucial in identifying and fixing the leak.