【发布时间】:2019-03-06 05:03:13
【问题描述】:
我对 C 编程很陌生。
我有一个任务,我们应该在其中创建一个整数的双向链表,并编写一些函数来操作它们。我们被要求防止内存泄漏,但我不确定如何做到这一点。
在制作链表时,我必须malloc 很多次才能创建和存储节点,而且我很确定malloc 为节点提供足够的空间然后释放节点不是一个好主意在同一个地方指向它。
因此,我最好的猜测是我应该释放主函数中的所有节点,当我将它们的内容打印到屏幕上并且不再需要它们时。我尝试实现一个kill 函数,它将对列表中第一个节点的引用head 作为输入,并迭代这些节点,并在它们运行时释放它们。
我什至安装了 valgrind 来尝试查看是否有任何内存泄漏,看起来还有一些。我不知道他们来自哪里或如何解决这个问题。
这是整个代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
struct Node *previous;
}Node;
void print_dll(Node *head){
Node *curr = head;
while(curr != NULL){
printf("%d\t", curr->data);
curr = curr->next;
}
puts(" ");
}
Node* create_dll_from_array(int array [], int arrSize){
//this is a function that creates a doubly linked list
//with the contents of the array
Node* current = (Node *) malloc (sizeof(Node * ));
current->data = array[arrSize-1];
current -> next = NULL;
for(int i = 2; i <= arrSize; i++){
//create a new node
Node * temp = (Node*)malloc(sizeof(Node*));
//I would like the dll to be in the same order as the array, I guess it isn't strictly necessary
temp ->data = array[arrSize-i];
temp -> next = current;
current-> previous = temp;
//now make temp the current
current = temp;
}
current-> previous = NULL;
return current;
}
void insert_after(Node* head, int valueToInsertAfter, int valueToInsert ){
if(head != NULL){
Node * current = head;
while(current-> data != valueToInsertAfter){
//this while loop brings 'current' to the end of the list if
//the searched value is not there
if(current-> next != NULL){
current = current->next;
}else{
break;
}
}
//after exiting this loop, the current pointer is pointing
//either to the last element of the dll or to the element
//we need to insert after
Node *new = (Node *) malloc (sizeof(Node *));
new->data = valueToInsert;
new->next = current->next;
new->previous = current;
if(current->next != NULL){
(current->next)->previous = new;
}
current->next = new;
}
}
void delete_element(Node* head, int valueToBeDeleted){
//work in progress
}
void kill(Node *head){
//this is my attempt at freeing all the nodes in the doubly linked list
Node *current;
while(head!=NULL){
current = head;
head = head->next;
free(head);
}
}
int main(){
int array [5] = {11, 2, 7, 22, 4};
Node *head;
/*Question 1*/
//creates a doubly linked list from the array below
head = create_dll_from_array(array, 5); ///size of the array is 5
/* Question 2 */
// print_dll(head);
/*Question 3*/
// to insert 13 after the first appearance of 7
insert_after(head, 7, 13);
print_dll(head);
//to insert 29 after first appearance of 21
insert_after(head, 21, 29);
print_dll(head);
/*Question 6*/
//create a function to free the whole list
kill(head);
return 0;
}
这里的主要功能是教授给我们的,我们必须围绕它构建功能。
我不知道为什么这似乎仍然会导致内存泄漏,如果我说实话,我真的不知道它们还会发生在哪里。据我所知,我需要将所有的记忆保留到几乎最后一分钟。
请帮忙,我在这里迷路了。
谢谢!
【问题讨论】:
标签: c pointers memory-management memory-leaks