オートグレーダーは、使用されているすべてのメモリを解放できなかったと言っています。どこでメモリリークが発生したのかわからないので、コード全体を次に示します。
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
、何かが解放されるたびにデクリメントされるグローバル整数を実装していました。誰かがメモリリークの可能性がある場所を指摘できれば、それは素晴らしいことです!