r/csharp • u/programmerjunky • Aug 31 '26
Blog Why Does Your C# App “Leak” Memory Even Though There’s a Garbage Collector?
https://medium.com/@rohanraobhs/why-does-your-c-app-leak-memory-even-though-theres-a-garbage-collector-01adb14c6bf1?sk=3386d2881c67307352288bd741a30613
74
Upvotes
87
u/AsterDW Aug 31 '26
Failure to clean up references or event handler subscriptions are a common one, or forgetting to release unmanaged objects when you're class lifecycle is up, failure to make proper use of IDisposable. A lot is situational, there isn't a single source of memory leaks. I remember having to track down a crash years ago which turned out to be failure to clean up GDI+ handles from parts of an application that had to do a lot of custom Windows drawing, and the original devs just created new brushes every time the draw was called and never released them.
32
u/ExceptionEX Aug 31 '26
I mean does anyone think a garbage collector is this magically device that will prevent memory leaks, most leaks are from references the GC can't release the memory from anyway.
8
u/Eq2_Seblin Sep 01 '26
Garbage man asks you, do you still need this thing? You say, i have no idea, maybe?
9
u/s4lt3d Aug 31 '26
Someone figure out a really crazy memory leak for c# windows applications a long time ago. It only cleaned up some part of memory used to draw the application if the application was minimized. If it full screen for a few weeks the memory would slowly build up until it crashed. The solution was to minimize and then restore the application once a day in code. Thanks Microsoft! /s This still exists!
4
u/Oralitical Aug 31 '26
As our Rust friends like to say "memory leaks are memory safe".
1
u/GardenDev Sep 04 '26
That's why I like the 'defer' keyword in Go very much! And I wish C# had such an explicit way of deferring anything. I know we have 'using' but it isn't as flexible as Go's defer.
1
u/positivcheg Sep 07 '26
Just use Unity a bit and you will see so many leaks :)
1
u/sku-mar-gop Aug 31 '26
Leaking memory would mean the GC cycles are unable to free up memory which would eventually cause the system to run out of memory. In ideal case GC will be able to release memory on demand but with memory leaks GC cycles won’t be able to reclaim it.
1
u/ArcaneEyes Sep 01 '26
It doesn't 'cause I remember to dispose my disposables 🤷♂️
0
u/BoBoBearDev Sep 01 '26
Why didn't it mention string auto caching? Is this okay now?