内存泄漏......解释(希望如此)

use*_*142 4 c garbage-collection memory-leaks memory-management

有人可以帮助我理解内存泄漏的概念以及特定数据结构如何促进/阻止它(例如链表,数组等).不久前我被两个不同的人教过两次 - 由于教学方法的不同,这让我有点困惑.

Vij*_*hew 7

维基百科对内存泄漏很好的描述.给出的定义是:

A memory leak, in computer science (or leakage, in this context), occurs 
when a computer program consumes memory but is unable to release it back 
to the operating system.
Run Code Online (Sandbox Code Playgroud)

例如,以下C函数泄漏内存:

void leaky(int n)
{
    char* a = malloc(n);
    char* b = malloc(n);
    // Do something with a
    // Do something with b
    free(a);
}
Run Code Online (Sandbox Code Playgroud)

n程序员忘记调用时,上述函数会泄漏内存字节free(b).这意味着操作系统的n字节数减少了以满足进一步调用的内存malloc.如果程序leaky多次调用,则操作系统最终可能会耗尽内存,以便为其他任务分配.

至于问题的第二部分,数据结构没有任何固有的东西可以使它们泄漏内存,但是粗心的数据结构实现可能会泄漏内存.例如,请考虑以下从链表中删除元素的函数:

// I guess you could figure out where memory is leaking and fix it.

void delete_element(ListNode* node, int key)
{
    if (node != NULL)
    {
        if (node->key == key)
        {
            if (node->prev != NULL) {
                // Unlink the node from the list.
                node->prev->next = node->next;
            }
        }
        else
        {
            delete_element(node->next, key);
        }  
    }
}
Run Code Online (Sandbox Code Playgroud)