0

私はこれに対して何が間違っているのかわかりません。私のプログラムは正しいように見えますが、valgrindによると、newNode関数にメモリリークがあるようです。newNode関数で何が間違っているのか、なぜ間違っているのかを知りたいです。

コードは次のとおりです。

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include "list.h"
typedef struct lnode {
   char *term;
   int count;
   int last;
   struct lnode *next;
}lnode,*lnodePtr;
/**
 * Returns a new linked list node filled in with the given word and line, and
 * sets the count to be 1. Make sure to duplicate the word, as the original word
 * may be modified by the calling function.
 */
 struct lnode *newNode (char* word, int line) {
    lnode *add=malloc(sizeof(lnode));
    add->term=(char *)malloc(strlen(word) + 1);
    strcpy((add -> term), word);
    add->count=1;
    add->last=line;
    add->next=NULL;
    return add;         
  }
  int main(int argc, char *argv[])
  {
    lnodePtr head=NULL; 
    char example[1000]="Name";
    char *ex=example;
    lnode *amc=newNode(ex,2);
    return(0);
  }

それで、私のメインだけで問題がありますが、私のnewNode関数では問題はありませんか?リンクリストは初めてなので、freeNodeの作成を手伝っていただけませんか。freeNodeは私のdeleteNodeに似ていると思いました(どうやらそれはメモリリークを修正しません)。私のdeleteNodeのコードは次のとおりです。

void deleteNode (struct lnode** head, struct lnode* node) {
    if(*head == NULL)
        return;

    if((node == *head)&&(((*head) -> next) != NULL)) 
    {
        *head = (*head) -> next;
    }
    else if((node == *head)&&(((*head) -> next) == NULL)) 
    {
        void *p = NULL;
        *head = (lnodePtr)p;
    }
    else
    {
        lnode *temp;
        temp=node;
        node=node->next;
        free(temp);
    }
    free(node);
}      
4

1 に答える 1

2

... newNode 関数でメモリ リークが発生しています ...

さて、( を使用して) メモリを割り当てましたが、( を使用してmalloc) 決して解放しませんでしたfree。それがメモリリークの定義です。

リークのないメインは次のようになります。

int main(int argc, char *argv[])
{
  lnodePtr head=NULL; 
  char example[1000]="Name";
  char *ex=example;
  lnode *amc=newNode(ex,2);
  // actual work?
  freeNode(amc);
}

さて、あなたfreeNodeも書くのに助けが必要ですか?

于 2013-02-25T11:10:20.447 に答える