That is not to say that garbage collection is an unambigous win. There are real downsides to using it. But for most programs, those modern garbage collectors are good enough that those downsides just don't matter.
Sure, you haven't lost the handle to the memory, but you can still "leak" memory with a GC. Happens all the time. Add to data structure at state 1, do something in state 2, remove data in state 3. What happens you never hit state 3?
> But for most programs, those modern garbage collectors are good enough that those downsides just don't matter.
I mostly agree with this. Although, most programs hit a point where you have to be aware what the GC is doing and try to avoid additional allocations. Which isn't very ergonomic at times. And is often more fucking around than manual memory management, just concentrated to a smaller portion of the code base.
Yes it is, by definition a memory leak is any memory that has been reserved but won't be read from or written to. If you allocate memory into a data structure and after some point in time you will never read from or write to that memory, then that memory constitutes a leak.
The upsides of the definition you gave are that it's simple, well defined, and maximally precise (nothing that is safe to collect is considered live)
The significant downside to this definition is that it's uncomputable. To know if memory is used requires knowing if a loop halts.
The second definition of memory leak is "unreachability" which is a bit harder to nail down. It's a conservative approximation of the first definition, but is more popular because it's computable, and it's practical to write programs with or without GC that don't leak
that's an useless definition as otherwise it would be trivial to augment, say, malloc to prevent memory leaks.
I would define a leak as unused memory that it is not otherwise reusable by a program.
What happens if you never escape a while loop? Should we ban while loop then? Bugs happen, we fix them. But I haven't had a memory bug in years outside of C and C++.
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...
I just recently updated a few small services to C# 12 and there's a bunch of little niceties like this I'm finding (spread operator for instance).
// Disposed when goes out of scope
using var http = new HttpClient();
var text = await http.GetStringAsync("https://example.org/");Swift as another one, RC is a GC algorithm, before the usual clueless reply from people not educated in CS.
Followed by FP languages now adopting effects and linear type systems, alongside their automatic memory management approaches.
function closure() {
var smallObject = 3;
var largeObject = Array(1000000);
function longLived() { return smallObject; }
function shortLived() { return largeObject; }
shortLived(); return longLived;
}
Will keep largeObject alive.You could test this with your code by setting a FinalizationRegistry to log when they're both finalized, unset any outside reference to `longLived`, and then do something to force a GC (like run Node with --expose-gc and call `global.gc()`, or just allocate a big Uint8Array).
You really do have to know the quirks of what you're targeting.
Well, the reference lua implementation handles this case fine, and it's a solid but not at all smart™ codebase.
> those modern garbage collectors are good enough that those downsides just don't matter.
This is not what I see. Every I look at a profile of a program written in a GCed language, most of the time is spent in the garbage collector. I can't recall the last time I looked at a c++ profile where more than 10% of the time spent in new/delete. I have seen 100x speedups by disabling GC. You can't ship that, but it proves there is massive overhead to garbage collection.
It doesn't have to be that way. The BEAM is designed for tiny processes, and GC is cheap.
Also, when your process has a giant heap, the GC gets expensive. There's been lots of improvement over the years, but I used to have processes that could usually go through N messages/sec, but if they ever got a backlog, the throughput would drop, and that would tend towards more backlog and even less throughput, and pretty soon it will never catch up.
That sometimes happens with other GC systems, but it never feels quite so dire.
Just like not all malloc()/free() were born equal, to the point companies did made big bucks selling specialised implementations.
I could have disabled the GC to get the same speed up.
It's easy to get in trouble with an interconnected object graph: you mess up and hold onto a pointer that you shouldn't be holding onto, which results in a leak.
Yes, logic bugs have the same issues, and even in languages like Java we can sometimes (albeit rarely IIRC) get memory leaks. But memory-safe languages are an improvement. Just like TypeScript is an improvement over JavaScript, even though they have the same semantics. We have automated systems that can decrease the amount of memory errors from 1% to 0.01%, why keep leak and UB prevention a manual concern? Moreover, the drawbacks of memory-safe languages are often not an issue: you can use a GC-based language like Java which is easy but has overhead, or an enforced-ownership language like Rust which has a learning curve but no overhead. Meanwhile, while logic bugs can be a PITA, memory bugs are particularly notorious, since they don’t give you a clear error message or in some cases even cause your program to halt when they occur.
Tangential: another solution that practically eliminated a class of bugs is formal verification. And currently we don’t see it in any system but those where correctness is most important, but that’s because unlike memory management the downsides are very large (extremely verbose, tricky code that must be structured a certain way or it’s even more verbose and tricky). But if formal verification gets better I believe that will also start to become more mainstream.
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.
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.
Edit: another one is swapping code by swapping class loaders. That can retain static references in the runtime class loader.
I think nowadays the only major languages that don't provide GC are C/C++, and one use them typically for their unrivaled performances, meaning performance is a more or less explicit requirement, so it is part of the problem domain.
There was C++/CX as well, with WinRT/COM reference counting, but it got killed in MS internal politics.
So projects to improve the quality, and lower the defect rate, in memory-managed programming, are far from wasted. Even if they only get used to write fast garbage collectors so that line coders can get on with the work of delivering value to customers.
1) Modern languages have made inroads here.
2) The OS is my automatic resource manager. When I hit ctrl-c on my running C program, my free() is never hit, yet it is cleaned up for me.
> So why complicate the design with automatic memory management?
I don't know beforehand who is going to be reading my memory, how many times, in what order, or whether they're going to copy out of it, or hold onto pointers into it.
> I just dont understand the fear with manual memory management. With RAII and and simple diligance (clear ownership rules), managing memory is an easy engineering task.
I claim that if managing memory is that straightforward, then it makes more sense to leave it to the compiler (Rust-style, not Java-style.) rather than let a human risk messing it up.
I mostly agree.
With RAII, memory management is simplified. "Just" evaluate the lifetime of the object. Super easy if you're good at software design.
Reference counting and shared pointers still have their niche use case. But I've most often seen referencing counting used as a crutch where reference-counting is _easy_ but designing around object lifetimes is more appropriate.
> Memory bugs are no worse than logic bugs
It's true. A memory bug is "just" another logic bug. Memory bugs lead to null pointers and wild pointers. They're just as dangerous as logic bugs. Memory bugs are also far more preventable with RAII.
> We do the same for OS resources (handles, sockets, etc) and dont use automatic resource managers, we do it manually. So why complicate the design with automatic memory management?
I'm just going to point out that I don't do manual allocations for OS resources. I wrap OS resources into RAII objects. I've made lots (!) of custom RAII wrappers for OS objects and library objects. It's trivial to do and saves a feckton of headaches.
C++ has std::fstream. I'm not saying it's great. But it's definitely RAII for files and has been around for... well I don't know exactly but certainly 25+ years.
The next level is going into linear types, which is what some GC first languages are now slowly looking into.
Generally, in most languages, file handles and sockets are automatically closed, when the variable holding them gets out of scope.
I can’t imagine manual memory management on these large scale projects with a high variance of developer scale and opinions.
I guess it comes down to what you mean by "worse". It seems that memory bugs carry a higher risk of being completely invisible except in deliberately contrived situations. This makes them more dangerous because there's less of an incentive to fix something that clients will never notice.
Do they really carry a higher risk of being invisible though? You don’t need to “contrive” situations either. My company just spent 6+ months trying to solve a JavaScript undefined symbol bug stemming from a library. When we finally tracked it down, it was because we were using import instead of require, which the documentation didn’t clarify was important. The fix we implemented was nowhere near where we expected the bug, and the only reason we finally solved it was because we had exhausted all other options. Sounds the same, if not worse, as a difficult to track memory bug to me.
Over my many years of working in software development I have come around to the idea that most software developers do not have sufficient working memory capacity to reason about memory management in addition to everything else they must reason about at the same time. They may know mechanically how to properly do manual memory management but when writing code they drop things if they are juggling too many things at once mentally. It isn't a matter of effort, there simply is a complexity threshold past which something has to give. Automatic memory management has its tradeoffs but it also enables some people to be effective who otherwise would not be.
On the other side of that you have the minority that get manual memory management right every time almost effortlessly, who don't grok why it is so difficult for everyone else because it is literally easy for them. I think some people can't imagine that such a group of engineers exist because they are not in that group and their brain doesn't work that way. If you are in this group, automatic memory management will seem to make things worse for unclear benefit.
I've observed this bifurcation in systems software my entire career. In discussions about memory safety and memory management, it is often erroneously assumed that the latter population simply doesn't exist.
Personally my gripe is when people don't think about memory or space complexity at all. I don't care if it's a custom memory management strategy or GC'd language, you need to think about it. I have the same gripe about persistence, socket programming, and database queries.
Abstractions are great, use them, love them. But understanding what the hell they are doing under the hood not only improves efficiency, it prevents bugs, and gives you a really solid base when reasoning about unexpected behavior.
And it can be tailored too if a situation really deserves it. If I'm doing something custom I want the smallest amount of code to verify, just the special memory manager and not everything that uses it.
These newcomers may have heard about it, may even understand it at some level, but it's not in their rote knowledge. GC is great if you know that every allocation you do is expensive and that you know that it will be taken care of properly, because it will be short-lived.
But I have seen many cases where people just don't have it in their conciousness why allocating huge arrays is a problem or why allocating a new Character object for every single character in a string might be bad. As soon as I point it out, they get it, but it's not like they thought of it while writing their algorithm.
-Brian Kernighan.
Sometimes all you can do is refactor around the problem until you can see it. Or push people to stop being that sort of clever in the first place and write more accessible code.
Unfortunately in the real C++ codebases I've had to work with, the flow of control is never so simple. Any correspondence between lexical scope and lifecycle is broken if the code uses exceptions, callbacks, any type of async, threads, etc.
Any deviation from that MUST be documented which includes seeing that as comments in code so people who read/maintain that code know what this is all about.
Thing is, many memory leaks are actually logic bugs and no (resource-)GC will save your bacon against these, in fact, you made your life more complicated through it because now you have to debug through another (abstraction) layer before getting to the true problem.
This is what this ownership in Rust is all about: It makes ownership visible to the programmer so they have to take care about it in a very explicit manner.
Why do you jump to that?
Why didn't you assume that they make errors like everyone, and simply deal with them?
Your ego is so fragile that it can't survive un the the same universe with the idea that someone somewhere might be living just fine without a crutch you apparently consider indispensable?
The fact is there are more than one way to detect and avoid errors reaching all the way to production. Every other human activity since humans existed employs them for thousands of years before golang existed. Rigor and discipline and methodology are not actually impossible. Shock!
You wouldn't say the same thing about stack push and pop would you? Memory management is kind of a solved problem for 99% of program. It only happens very rarely and under very constrained environment.
Yes, I did encountered a stack overflow error because I didn't realize the size of the struct is gigantic. So I solved it by creating the object on the heap instead. Similarly, memory "bugs" in managed systems is very rare and they can mostly be solved.
Every time a managed systems have issues, we get blog posts like this exactly because they are rare. If I write a blog post every time I have encountered a memory leak in a C program, well no one really cares. It's kind of expected.
I create it, I free it. I transfer, I no longer care. Its part of engineering discipline. Memory bugs are no worse than logic bugs, we fix the logic bugs, makes sense to fix the memory bugs. Disclaimer: I do embedded complex systems that run 24/7.
We do the same for OS resources (handles, sockets, etc) and dont use automatic resource managers, we do it manually. So why complicate the design with automatic memory management?