What is a memory leak?

πŸ’‘ Concept: Memory Leak

A memory leak happens when your program keeps holding references to objects that it no longer needs. Since the garbage collector only frees memory for unreferenced objects, those β€œstuck” references prevent cleanup and gradually eat up memory.

πŸ“˜ Quick Intro

In C#, memory leaks don’t usually happen because of raw pointer misuse (like in C++). Instead, they occur when objects stay alive unintentionally. Left unchecked, this leads to higher memory usage, slower performance, and eventually app crashes.

🧠 Analogy

Imagine never throwing away old files from your desk. Even if you don’t need them, they keep piling up until your desk is unusable. That’s what a memory leak is β€” holding onto things you should’ve let go.

πŸ”§ Technical Breakdown

  • πŸ—‘οΈ The garbage collector can’t free memory if objects are still referenced.
  • πŸ”— Common causes:
    • Forgetting to -= unsubscribe from event handlers
    • Static fields keeping objects alive
    • Unreleased unmanaged resources (file handles, DB connections)
  • πŸ“‰ Symptoms: memory keeps growing, performance slows down, app eventually crashes.
  • πŸ› οΈ Detection: profiling tools like dotMemory, PerfView, or Visual Studio diagnostics.
  • βœ… Prevention: explicitly release references, implement IDisposable, and always unsubscribe from events.

🎯 Use Cases

  • βœ… Diagnosing performance issues in long-running apps.
  • βœ… Ensuring proper disposal of event subscriptions.
  • βœ… Preventing out-of-memory exceptions.
  • βœ… Writing memory-efficient C# code.
  • βœ… Keeping long-running apps (like web servers) stable over time
  • βœ… Writing clean, memory-efficient C# code
  • βœ… Avoiding production outages from OutOfMemoryException
  • βœ… Debugging performance issues that are hard to trace

πŸ’» Code Example


// Event subscription causing memory leak if not unsubscribed
class Publisher {
    public event EventHandler RaiseEvent;
}

class Subscriber {
    public void Subscribe(Publisher pub) {
        pub.RaiseEvent += HandleEvent;
    }

    private void HandleEvent(object sender, EventArgs e) { /*...*/ }

    public void Unsubscribe(Publisher pub) {
        pub.RaiseEvent -= HandleEvent;
    }
}

❓ Interview Q&A

Q1: What is a memory leak?
A: Unreleased memory due to persistent references.

Q2: What causes memory leaks in C#?
A: Event handlers, static references, unmanaged resources.

Q3: How to detect memory leaks?
A: Using profiling and diagnostic tools.

Q4: How to prevent memory leaks?
A: Properly unsubscribe events and dispose objects.

Q5: Can garbage collection fix leaks?
A: No, GC only collects unreferenced objects.

Q6: What is event subscription leak?
A: Forgetting to unsubscribe keeps objects alive.

Q7: Is static reference a cause?
A: Yes, it keeps objects rooted.

Q8: Can unmanaged code cause leaks?
A: Yes, if not managed correctly.

Q9: What happens if memory leaks?
A: Performance degradation and crashes.

Q10: How to avoid leaks?
A: Follow best practices for resource management.

πŸ“ MCQs

Q1. What is a memory leak?

  • Released memory
  • Unreleased memory
  • Memory allocation
  • Garbage collection

Q2. What causes memory leaks?

  • Loops
  • Event handlers and static references
  • Threads
  • Exceptions

Q3. How to detect memory leaks?

  • Debug logs
  • Profiling tools
  • Unit tests
  • Code review

Q4. How to prevent memory leaks?

  • Ignore
  • Unsubscribe events
  • Use static
  • Restart app

Q5. Can GC fix leaks?

  • Yes
  • No
  • Sometimes
  • Never

Q6. What is event subscription leak?

  • Unsubscribing
  • Not unsubscribing
  • Garbage collecting
  • Allocating

Q7. Is static reference a leak cause?

  • No
  • Yes
  • Sometimes
  • No idea

Q8. Can unmanaged code cause leaks?

  • No
  • Yes
  • Sometimes
  • No idea

Q9. What happens if memory leaks?

  • Better performance
  • Performance issues
  • No effect
  • Crash

Q10. How to avoid leaks?

  • Ignore
  • Proper resource management
  • Use more memory
  • Restart system

πŸ’‘ Bonus Insight

In C#, leaks often hide in plain sight β€” especially with events and statics. Reviewing code with a β€œlifecycle mindset” (who creates this, who cleans it up?) is the simplest way to avoid them. Remember: the garbage collector isn’t magic β€” it only collects what you let go of.

Being aware of memory leaks and proactively managing event subscriptions and references is key to robust C# applications.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ” Navigation

Learn More About C# πŸ“š

1. What is C#? πŸ‘‰ Explained
2. Main Features of C# πŸ‘‰ Explained
3. Difference Between C# and Java πŸ‘‰ Explained
4. Common Language Runtime (CLR) in C# πŸ‘‰ Explained
5. Common Type System (CTS) in C# πŸ‘‰ Explained
6. Common Language Specification (CLS) in C# πŸ‘‰ Explained
7. Value Types vs Reference Types in C# πŸ‘‰ Explained
8. What is a Namespace in C#? πŸ‘‰ Explained
9. Purpose of the 'using' Keyword in C# πŸ‘‰ Explained
10. Different Data Types in C# πŸ‘‰ Explained
11. Difference Between int and Int32 in C# πŸ‘‰ Explained
12. Difference Between float, double, and decimal in C# πŸ‘‰ Explained
13. What is the Default Value of a Boolean in C#? πŸ‘‰ Explained
14. What is Boxing and Unboxing in C# πŸ‘‰ Explained
15. What are the Different Types of Operators in C# πŸ‘‰ Explained
16. Difference Between Equals and == in C# πŸ‘‰ Explained
17. What is the Null-Coalescing Operator ?? in C# πŸ‘‰ Explained
18. What is the Ternary Operator in C# πŸ‘‰ Explained
19. How Does the Switch Statement Work in C# πŸ‘‰ Explained
20. What is Object-Oriented Programming in C# πŸ‘‰ Explained
21. What are the Four Pillars of OOP in C# πŸ‘‰ Explained
22. What is Encapsulation in C# πŸ‘‰ Explained
23. What is Inheritance in C# πŸ‘‰ Explained
24. What is Polymorphism in C# πŸ‘‰ Explained
25. What is Abstraction in C# πŸ‘‰ Explained
26. What is an Abstract Class in C# πŸ‘‰ Explained
27. What is an Interface in C# πŸ‘‰ Explained
28. Can a Class Implement Multiple Interfaces in C#? πŸ‘‰ Explained
29. Difference Between Abstract Class and Interface in C# πŸ‘‰ Explained
30. How Do You Create a Class in C#? πŸ‘‰ Explained
31. What is a Constructor in C# πŸ‘‰ Explained
32. What Are the Types of Constructors in C# πŸ‘‰ Explained
33. What is a Static Constructor in C# πŸ‘‰ Explained
34. Difference Between Static and Non-Static Members in C# πŸ‘‰ Explained
35. What is the Use of 'this' Keyword in C# πŸ‘‰ Explained
36. What is a Destructor in C# πŸ‘‰ Explained
37. What is Object Initializer Syntax in C# πŸ‘‰ Explained
38. What is the Difference Between Field and Property in C# πŸ‘‰ Explained
Share:

Tags:


Feedback Modal Popup