๐Ÿ’ป Programming

Memory Leak

Memory Leak

A bug in which unused memory is not released. The system slows down over time.

๐Ÿ“– Detailed Explanation

A memory leak (Memory Leak) is a bug that occurs when a program fails to release dynamically allocated memory even though it is no longer used. As a result, the memory available while the program runs keeps decreasing, and in severe cases it can cause system-wide performance degradation or crashes.

The main causes of memory leaks include unreleased references. Typical examples are cases where references to an object remain so the garbage collector cannot reclaim it, cases of event listeners not being released where a DOM element has been removed but the event handler remains, and cases of variable references inside closures that needlessly reference large objects from an outer scope.

Memory management differs by programming language. Languages such as JavaScript, Java, and Python manage memory automatically through garbage collection (GC), but if references remain, even GC cannot reclaim the memory. Languages such as C and C++, on the other hand, require manual memory management, so you must explicitly call malloc/free or new/delete, and incorrect management causes memory leaks or dangling pointer problems.

There are various tools for detecting memory leaks. Valgrind is a powerful tool for detecting memory errors in C/C++ programs, and the Memory tab in Chrome DevTools lets you find leaks by analyzing JavaScript heap snapshots. In Node.js, you can use Chrome DevTools with the --inspect flag or use tools such as clinic.js.

๐Ÿ’ป Code Example

Here are common memory leak patterns in JavaScript and how to fix them:

memory-leak-example.js - memory leak example
// ๋ฌธ์ œ 1: ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ ๋ฏธํ•ด์ œ
class LeakyComponent {
    constructor() {
        this.data = new Array(10000).fill('large data');

        // ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ ๋“ฑ๋ก - ํ•ด์ œํ•˜์ง€ ์•Š์œผ๋ฉด ๋ˆ„์ˆ˜ ๋ฐœ์ƒ!
        window.addEventListener('resize', this.handleResize);
    }

    handleResize = () => {
        console.log('Resized!', this.data.length);
    }
}

// ๋ฌธ์ œ 2: ํด๋กœ์ €์—์„œ์˜ ์ฐธ์กฐ ์œ ์ง€
function createClosure() {
    const hugeArray = new Array(1000000).fill('data');

    // ํด๋กœ์ €๊ฐ€ hugeArray๋ฅผ ์ฐธ์กฐํ•˜์—ฌ GC ๋ถˆ๊ฐ€
    return function() {
        return hugeArray[0];
    };
}

// ๋ฌธ์ œ 3: setInterval ๋ฏธ์ •๋ฆฌ
function startPolling() {
    const cache = [];

    setInterval(() => {
        // ๊ณ„์† ๋ฐ์ดํ„ฐ๊ฐ€ ์Œ“์ด๋ฉฐ ๋ฉ”๋ชจ๋ฆฌ ์ฆ๊ฐ€
        cache.push(new Array(1000).fill(Math.random()));
    }, 1000);
}
memory-leak-fixed.js - memory leak fixed
// ํ•ด๊ฒฐ 1: ์ปดํฌ๋„ŒํŠธ ์ •๋ฆฌ(cleanup) ํŒจํ„ด
class SafeComponent {
    constructor() {
        this.data = new Array(10000).fill('large data');
        this.handleResize = this.handleResize.bind(this);
        window.addEventListener('resize', this.handleResize);
    }

    handleResize() {
        console.log('Resized!', this.data.length);
    }

    // ๋ฐ˜๋“œ์‹œ cleanup ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ๋ฆฌ์Šค๋„ˆ ํ•ด์ œ
    destroy() {
        window.removeEventListener('resize', this.handleResize);
        this.data = null; // ๋ช…์‹œ์  ์ฐธ์กฐ ํ•ด์ œ
    }
}

// ํ•ด๊ฒฐ 2: WeakRef ๋˜๋Š” ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋งŒ ์ฐธ์กฐ
function createSafeClosure() {
    const hugeArray = new Array(1000000).fill('data');
    const firstItem = hugeArray[0]; // ํ•„์š”ํ•œ ๊ฐ’๋งŒ ์ €์žฅ

    return function() {
        return firstItem; // hugeArray ์ฐธ์กฐ ์—†์Œ
    };
}

// ํ•ด๊ฒฐ 3: interval ID ์ €์žฅ ๋ฐ ์ •๋ฆฌ
function startSafePolling() {
    const cache = [];
    const MAX_CACHE_SIZE = 100;

    const intervalId = setInterval(() => {
        if (cache.length >= MAX_CACHE_SIZE) {
            cache.shift(); // ์˜ค๋ž˜๋œ ๋ฐ์ดํ„ฐ ์ œ๊ฑฐ
        }
        cache.push(new Array(1000).fill(Math.random()));
    }, 1000);

    // cleanup ํ•จ์ˆ˜ ๋ฐ˜ํ™˜
    return () => clearInterval(intervalId);
}

๐Ÿ—ฃ๏ธ Examples of Practical Conversations

Meeting: analyzing the cause of a performance issue
PM: In production, the server keeps getting slower and slower and eventually crashing.
Senior developer: That's a classic memory leak symptom. Have you checked the memory usage trend on the monitoring dashboard?
DevOps: Yes, after deployment memory keeps increasing as time passes until the process is terminated by OOM (Out of Memory).
Senior developer: Since it's a Node.js server, let's take heap snapshots with the --inspect flag and compare them. We can see which objects keep piling up.
PM: Once you find the cause, please also add monitoring alerts to prevent recurrence.
Interview: experience detecting and fixing memory leaks
Interviewer: Have you ever experienced a memory leak in production? Please explain how you found and fixed it.
Candidate: Yes, in an SPA, memory kept increasing even after navigating between pages. When I took two heap snapshots in the Memory tab of Chrome DevTools and compared them, component instances from the previous page kept remaining.
Interviewer: What was the cause?
Candidate: It was because a resize event listener registered on window was not released when the component unmounted. I added removeEventListener in the useEffect cleanup function and introduced a lint rule across the team to prevent recurrence.
Code review: finding a memory leak pattern
Reviewer: This component registers an event listener with useEffect, but there is no cleanup function.
Author: Oh, I thought it would be cleaned up automatically when the component unmounts.
Reviewer: The DOM element is removed, but event listeners registered on window or document have to be released manually. Otherwise the handler stays in memory even after the component is gone.
Author: So should I call removeEventListener in the return statement?
Reviewer: Yes, and the same goes for setInterval. Always call clearInterval in the cleanup function.

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Cautions

  • Releasing event listeners is mandatory
    Handlers registered with addEventListener must be released with removeEventListener. Handle this in the useEffect cleanup function in React and in onUnmounted in Vue.
  • Managing closure references
    If a closure references a large object from an outer scope, GC cannot reclaim it. Copy only the values you need, or explicitly assign null after use.
  • Clean up timers/intervals
    Store the IDs of setInterval and setTimeout, and call clearInterval and clearTimeout when the component is released. Infinite polling can become a memory bomb.
  • Beware of DOM references
    If JavaScript references to removed DOM elements remain, the memory is not released. Clean up reference variables after DOM manipulation.
  • Limit cache size
    Always set a maximum size for memory-based caches and remove old data with a policy such as LRU.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More