什么是内存泄漏?(What is a memory leak?)

程序中的内存泄漏是怎么回事呢?

我们写过很多带有关键词free()的程序。比如我在这篇博文关于链表的一些重要操作(Important operations on a Linked List)中删除整个链表用到这个函数,代码片断如下:

struct node * deleteList(struct node * head)
{
    struct node * temp;
    while(head != NULL)
    {
        temp = head;
        head = head -> next;
        free(temp);
    }
    return NULL;
}

我们在程序中分配内存时,程序结束后并不会自动释放手动分配的内存,所以我们也要手动去释放我们分配的内存。有些情况下程序会一直运行下去,那么就会发生内存泄漏。当程序员在堆中分配内存却忘了释放就会发生内存泄漏。对于像守护进程和服务器这样的程序设计之初就是长时间运行的程序内存泄漏是很严重的问题。

下面是会产生内存泄漏代码的例子:

void func()
{
    // in the below line we allocate memory
    int *ptr = (int *) malloc(sizeof(int));
 
    /* Do some work */
 
    return; // Return without freeing ptr
}
// We returned from the function but the memory remained allocated.
// This wastes memory space.

避免内存泄漏正确的代码:

void func()
{
    // We allocate memory in the next line
    int *ptr = (int *) malloc(sizeof(int));
 
    /* Do some work */
 
    // We unallocate memory in the next line
    free(ptr);
 
    return;
}
释放自己分配的内存在C语言中是一个好的习惯。
原文地址:https://www.cnblogs.com/programnote/p/4721140.html