可能重复: 在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);发布于 2012-12-08 19:49:16
在它提供的众多特性中,瓦兰将允许您使用检查内存泄漏。它通过动态地检测内存管理功能来做到这一点。
您可以使用这样的命令:
valgrind --tool=memcheck --leak-check=yes my_prog发布于 2012-12-08 19:51:13
如果您想要释放内存,您可以调用空闲()函数来释放内存,或者调用dealloc()函数,它也释放内存,并且您正在使用函数,因此您创建的指针变量仅限于该函数的作用域,一旦函数终止,该函数将自动释放。
https://stackoverflow.com/questions/13781227
复制相似问题