c - 我如何确定我已经释放了所有在 C 中分配的内存?

标签 c list memory-management

<分区>

Possible Duplicate:
What is the best way to check for memory leaks in c++?

我正在用 C 编写一个双向链表,其中大部分已实现并且可以正常工作(我只需要修复遍历和可能释放时的一些小逻辑错误)。

问题: 我怎样才能绝对确定我正在释放我分配的所有内存?我还想知道是否有任何技术可以优化我的分配。任何有关其工作原理或教程链接的提示或提示也将受到赞赏。

我几乎是一个初学者,所以任何其他修复我的编码技术的技巧都将不胜感激。我使用 gdb 进行调试,并且在 Archbang Linux x86_64 上运行。

感谢您的帮助。

这里是双向链表的结构:

typedef struct node_element{
    double data;
} element;

typedef struct node_t{
    struct node_t *prev;
    struct node_t *next; 
    struct node_element element;
} node;

typedef struct list_t{
    struct node_t *head;
    struct node_t *tail;
} list;

这是我创建列表的方式:

list *createList(){
    list *temp = malloc(sizeof(list));

    temp->head = malloc(sizeof(node));
    temp->tail = malloc(sizeof(node));

    temp->head->prev = NULL;
    temp->head->next = temp->tail;
    temp->tail->prev = temp->head;
    temp->tail->next = NULL;

    return temp;
}

新节点:

node *newNode(element * element){
    node *current = malloc(sizeof(node));
    current->element.data = element->data;

    return current;
}

删除单个节点,与我的问题不太相关,但可能有用:

node *removeNode(list * list, node * current){
    if (current->prev == NULL)
        list->head = current->next;
    else
        current->prev->next = current->next;

    if (current->next == NULL)
        list->tail = current->prev;
    else
        current->next->prev = current->prev;

    free(current);

    return NULL;
}

现在是重要的部分,当我完成一个列表时,我调用这个函数:

list *removeList(list * list){
    node *temp; //Revised.
    //node *temp = malloc(sizeof(node));

    while (list->head != NULL){
        temp = list->head->next;
        free(list->head);
        list->head = temp;
    }

    return NULL;
}

像这样:

a_list = removeList(a_list);

最佳答案

在它提供的众多功能中,Valgrind将允许您 check for memory leaks .它通过动态检测内存管理功能来实现这一点。

你可以使用这样的命令:

valgrind --tool=memcheck --leak-check=yes my_prog

关于c - 我如何确定我已经释放了所有在 C 中分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13781227/

相关文章:

c - 在 C 中交换一维数组的列/行

c - C中正态分布的错误答案

c++ - 使用 C++ 从文件读取到单个内存块

c - 如何通过2层函数修改结构体内容?

c - 如何在 C 中翻转一个字节中的特定位?

c# - C# 中的高级列表比较

java - ArrayList<Number> 是什么意思?

r - 如何在 R 编程中将对象添加到列表中?

optimization - 我的Grails应用程序在启动时使用200 MB以上的内存是否正常?

gcc - 如何在数据部分(RAM)中保留一定范围的内存并防止使用该内存的同一应用程序的堆/堆栈?