Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

By far, the worst memory leak I’ve ever had to debug involved a cycle like you are describing, but it was in a Java program (swing encourages/encouraged such leaks, and “memory leaks in java are impossible”, so there weren’t decent heap profilers at the time).

For the last few decades, I’ve been writing c/c++/rust code, and the tooling there makes it trivial to find such things.

One good approach is to use a C++ custom allocator (that wraps a standard allocator) that gets a reference to a call site specific counter (or type specific counter) at compile time. When an object is allocated it increments the counter. When deleted, it decrements.

Every few minutes, it logs the top 100 allocation sites, sorted by object count or memory usage. At process exit, return an error code if any counters are non-zero.

With that, people can’t check in memory leaks that are encountered by tests.

In practice, the overhead of such a thing is too low to be measured, so it can be on all the time. That lets it find leaks that only occur in customer environments.



But circular references don't leak in Java. You have to have a GC root (e.g. a static, or something in your runtime) somewhere pointing at the thing to actually leak it.

There is one case where a "circular" reference can appear to cause a leak that I know of: WeakHashMap. But that's because the keys, which are indeed cleaned up at some point once the associated value is GC'd, are themselves strongly retained references.


ThreadLocal can be another problem. Tomcat kills and recreates threads for this reason.

Edit: another one is swapping code by swapping class loaders. That can retain static references in the runtime class loader.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: