自动分级机告诉我我未能释放所有使用的内存。我不确定我在哪里造成了内存泄漏,所以这是我的整个代码:
struct lnode {
int count;
int line;
char* word;
struct lnode* next;
};
struct lnode* newNode(char* word, int line) {
struct lnode* temp = (struct lnode*)malloc(sizeof(struct lnode));
char* newWord = (char*)malloc(strlen(word) + 1);
newWord = strcpy(newWord, word);
temp->word = newWord;
temp->line = line;
temp->count = 1;
return temp;
}
void pushNode(struct lnode** head, struct lnode* node) {
node->next = *head;
*head = node;
}
struct lnode* getNode(struct lnode* head, char* word) {
struct lnode* current = head;
char* temp = (char *)malloc(strlen(word));
strcpy(temp, word);
while(current != NULL) {
if(!strcmp(nodeGetWord(current),temp))
return current;
current = nodeGetNext(current);
}
return NULL;
}
char* nodeGetWord(struct lnode* node) {
return node->word;
}
struct lnode* nodeGetNext(struct lnode* node) {
return node->next;
}
int nodeGetLine(struct lnode* node) {
int line = node->line;
return line;
}
int nodeGetCount(struct lnode* node) {
return node->count;
}
void nodeSetCount(struct lnode* node, int count) {
node->count = count;
}
void nodeSetLine(struct lnode* node, int line) {
node->line = line;
}
void deleteList(struct lnode** head) {
struct lnode* current = *head;
struct lnode* next;
while(current) {
next = current->next;
free(current);
current = next;
}
*head = NULL;
}
void deleteNode(struct lnode** head, struct lnode* node) {
struct lnode* currentNode = *head;
struct lnode* previousNode = NULL;
while (currentNode != NULL) {
if (currentNode != node) {
previousNode = currentNode;
currentNode = nodeGetNext(currentNode);
continue;
}
if (previousNode)
previousNode->next = node->next;
else
*head = node->next;
free(node);
break;
}
}
void printList(struct lnode** head) {
struct lnode* current = *head;
while (current != NULL) {
printf("%s\n",nodeGetWord(current));
current = nodeGetNext(current);
}
}
int main() {
struct lnode* head = NULL;
struct lnode* a = newNode("Hello",3);
pushNode(&head, a);
struct lnode* b = newNode("Hi",2);
pushNode(&head, b);
struct lnode* c = newNode("Hola",4);
pushNode(&head, c);
struct lnode* d = newNode("Yo",5);
pushNode(&head, d);
struct lnode* e = newNode("Bye", 7);
pushNode(&head, e);
printList(&head);
//deleteNode(&head,e);
//printf("key: %s\n",nodeGetWord(e));
//printf("\n");
deleteList(&head);
printf("\n");
printList(&head);
printf("\nDone\n");
}
main 和 printList() 函数可以忽略,因为当我将其提交给自动评分器时,它们已被注释掉——它们仅用于测试目的。一切似乎对我来说都正常。我什至实现了一个全局整数,每当我有东西时它就会更新malloc
,而每当有东西被释放时它就会递减。如果有人能指出可能的内存泄漏在哪里,那就太好了!