Why does leaked memory appear malloced to kernel_task, and why can't OS X therefore garbage collect it

The core of OS X is not garbage collected; IOKit's libkern C++ Runtime requires developers to manage their own memory.

Mac Memory Management

From How does memory management work in Mac OS X?

Apple documents the lowest levels of the Mach Kernel and the virtual memory subsystem fairly well on the web as part of it's developer documentation.

  • Kernel Programming Guide: Memory and Virtual Memory

Since that kernel was developed by Carnegie Mellon University, you can find dozens of papers describing it quite easily.

Other Sources

  • Wikipedia discusses Mac OS memory management.

  • Apple's support note: Use Activity Monitor to read system memory and determine how much RAM is being used

Garbage Collection

Garbage collection exists at the user or application layer. Even at this layer, garbage collection only helps if the application has released all claims to the memory. A circular dependancy can defeat garbage collection. Garbage collection itself is an evolving area of research and difficult to get right.

Report Bugs and Memory Leaks

Bugs within OS X will be leaking memory. Given the size of the code base, this is almost certain.

Please report reproducible bugs directly to Apple. Every bug report helps and maybe your example will be the one that helps Apple's engineers pin down the cause.


Here's my guess, assuming your Mac has an integrated GPU (eg Intel Iris Graphics).

When you have your thesis open in Preview, graphics card memory is used to hold the image ("texture") of the Preview window, and perhaps also some off-screen-but-decoded pages from the thesis.

With an integrated graphics card, the video memory is actually (partially?) located in system RAM, which is shared between the CPU and GPU. On some integrated graphics cards, the amount of system RAM used is dynamically allocated (see Apple HT204349).

I'd guess that you are intermittently seeing a bug in the graphics card driver and/or Preview, which isn't releasing system memory correctly when Preview reloads your thesis PDF. (However this bug is mitigated by OS X / the driver correctly releasing the memory when Preview quits.)

You could try looking at the output of kextstat and see if the numbers in the Size column increase when you experience the issue. My theory is that the 8GB increase you mention will be due to the graphics card driver.

The following command (from a comment on this related and interesting answer) sorts the output of kextstat to make it easier to see which kext is using the most memory (although note this sorts by the Wired column... there's a similar, simpler incantation in this answer with an explanation if you'd like to tweak this).

kextstat | awk 'NR==1{ printf "%10s %s\n", $5, $6; } NR!=1{ printf "%10d %s\n", $5, $6; }' | sort -n