• Sloth Bytes
  • Posts
  • đŸŠ„ What Is Memory and Why Does It Leak?

đŸŠ„ What Is Memory and Why Does It Leak?

Sponsored by

Hello fellow sloths!

Welcome to this week’s Sloth Bytes. I hope you had an amazing week! 😁 

Your career will thank you.

Over 4 million professionals start their day with Morning Brew—because business news doesn’t have to be boring.

Each daily email breaks down the biggest stories in business, tech, and finance with clarity, wit, and relevance—so you're not just informed, you're actually interested.

Whether you’re leading meetings or just trying to keep up, Morning Brew helps you talk the talk without digging through social media or jargon-packed articles. And odds are, it’s already sitting in your coworker’s inbox—so you’ll have plenty to chat about.

It’s 100% free and takes less than 15 seconds to sign up, so try it today and see how Morning Brew is transforming business media for the better.

What Is Memory and Why Does It Leak?

Ever wondered why your computer gets slower after running for days? Or why that game you're playing starts stuttering after a few hours? Or why your C++ program error says this:

5 bytes in 1 blocks are definitely lost in loss record 1 of 1

Congrats, you've met the memory leak!

One of programming's silent killer.

Let's talk about what memory actually is, why it "leaks," and how to stop your programs from becoming digital hoarders.

Memory: Your Program's Workspace

Think of your computer's memory (RAM) like a massive whiteboard. When your program runs, it writes stuff on the board:

name = "Sloth"           # Write "Sloth" on the board
score = 100             # Write "100" somewhere else
inventory = ["sword"]   # Write a list over here

Unlike your hard drive (permanent storage), RAM is temporary. When your program ends, the whole whiteboard gets erased. Fresh start.

The Problem: Memory leaks

The term "Memory leak" is misleading.

The memory isn't leaking out, it's just stuck where you can't use it. Like that gym membership you keep paying for but never use.

In a perfect world, your program would erase things when it's done with them. But sometimes... it forgets.

“But my language has garbage collection đŸ€“ đŸ‘†ïž “

Garbage collection (gc) does handle a lot of the cleanup work for you!

Usually


However you can still leak memory by keeping references (hoarding):

all_results = []

def analyze_data(filename):
    huge_data = load_file(filename)  # Pretend it's 500MB
    result = process(huge_data)      
    all_results.append(huge_data)    # Why keep this?
    return result
# We never remove the data from all_results...

Every file you analyze adds 500MB to memory. Forever. We never clean it up. That's a leak.

The gc won’t do anything since it thinks you’ll use that reference later.

Your program is now a digital hoarder, keeping everything "just in case."

Common Memory Leak Patterns

The Hoarder (Java example):

class Cache {
    List<Data> cache = new ArrayList<>();
    
    void addData(Data d) {
        cache.add(d);  // Grows forever
        // We never empty the cache!
    }
}

The Forgetter:

void processFile() {
    char* buffer = malloc(1000000);
    // We forgot to free(buffer)!
}

The Circular Trap:

class Node:
    def __init__(self):
        self.child = None

parent = Node()
child = Node()
parent.child = child
child.parent = parent  

# Causes a circular cycle/loop!
# There's never an "end point"

Common fixes to memory leaks

1. Use Context Managers (Python):

# Automatically cleans it up (opens and closes the file)
with open('file.txt') as f:
    data = f.read()

2. Adding a limit:

if (cache.size() > 1000) {
    cache.remove(0);  // Remove old stuff
}

3. Clear References

char* buffer = malloc(1000);
// Use buffer
free(buffer);        // Free the memory
buffer = NULL;       // Clear the pointer

4. Clean Up Events/Timers:

// Start
const timer = setInterval(check, 1000);

// Stop (don't forget this!)
clearInterval(timer);

Why Should You Care?

Small leak in a quick script? No big deal. Your OS cleans up when the program ends.

But in long-running programs (servers, games, desktop apps, embedded systems), those leaks add up:

  • Game starts at 60 FPS, drops to 15 FPS after 2 hours

  • Server crashes every few days

  • Your Arduino project “mysteriously” stops working

  • Desktop app using 8GB of RAM for no reason

How to Spot a Leak

The Symptoms:

  • Program gets slower over time

  • Memory usage only goes up, never down

  • Eventually: crash or "out of memory" error

Helpful Tools

  • Task Manager / Activity Monitor (quick check)

  • Profilers (Valgrind for C/C++, memray for Python)

  • Built-in tools (gc module in Python, heap dumps in Java)

The Bottom Line

Memory leaks = your program is a hoarder. It keeps everything "just in case" until it runs out of space and crashes.

Watch out for:

  • Collections that only grow

  • Forgotten file handles

  • Event listeners/timers that run forever

  • Circular references

Most modern languages help prevent leaks, but they can't fix bad habits.

Remember: Every byte you allocate is space on the whiteboard. Make sure you're erasing stuff you don't need.

Thanks for the feedback!

Thanks to everyone who submitted!


Next in the Alphabet

Create a function which returns the next letters alphabetically in a given string. If the last letter is a "Z", change the rest of the letters accordingly.

Examples

next_letters("A")
output = "B"
// 'A' becomes 'B' – simple increment.

next_letters("ABC")
output = "ABD"
// 'C' becomes 'D' – last character changes without carry.

next_letters("Z")
output = "AA"
// 'Z' rolls over to 'A', and since there's no previous letter, we add a new 'A'.
// Think of it like 9 + 1 = 10, here Z + 1 = AA.

next_letters("CAZ")
output = "CBA"
// 'Z' → 'A' (carry), 'A' → 'B' (no carry), so "CAZ" becomes "CBA".
// Like incrementing 129 → 130 but in letters.

next_letters("")
output = "A"
// Empty input is treated as 0 → return 'A'.

Notes

  • Tests will all be in CAPITALS.

  • Empty inputs should return a capital "A" (as if it were in letter position 0!).

  • Think about the letter "Z" like the number 9 and how it carries over to increment the next letter/digit over.

How To Submit Answers

Reply with

  • A link to your solution (github, twitter, personal blog, portfolio, replit, etc)

  • or if you’re on the web version leave a comment!

  • If you want to be mentioned here, I’d prefer if you sent a GitHub link or Replit!

New video this week hopefully!

Recently hired an editor, so I’m hoping I can start uploading consistently 😃 

That’s all from me!

Have a great week, be safe, make good choices, and have fun coding.

If I made a mistake or you have any questions, feel free to comment below or reply to the email!

See you all next week.

What'd you think of today's email?

Login or Subscribe to participate in polls.

Want to advertise in Sloth Bytes?

If your company is interested in reaching an audience of developers and programming enthusiasts, you may want to advertise with us here.

Reply

or to participate.