1

dict_free()関数でメモリの割り当てを解除しようとしましたが、機能せず、理由もわかりません。私は何かが足りないのですか?何が悪いのか理解できません。

編集:dict_free()でfree()を呼び出すと、free'dポインターがNULLを指していることがわかりますが、それは起こりません。

これが私のコードです:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Dict
{
  struct Dict *branches[256];
  int index;

}Dict;


void dict_insert_depth(unsigned char*,Dict *,int);
void dict_insert(unsigned char*,Dict *);

void dict_free(Dict *d)
{
  if(d!=NULL){
    int i;
    for(i=0; i<256; i++){
      if(d->branches[i] != NULL){
        dict_free(d->branches[i]);
        free(d->branches[i]);
        printf("Is it free??  %s\n",d==NULL?"yes":"no");
      }
    }
  }
}
/**
 * Insert word into dictionaR
 */
void dict_insert(unsigned char *w, Dict *d)
{
  dict_insert_depth(w,d,0);
}

void dict_insert_depth(unsigned char *w, Dict *d, int depth)
{
  if(strlen(w) > depth){
    int ch = w[depth];

    if(d->branches[ch]==NULL){
      d->branches[ch] = malloc(sizeof(struct Dict));
      dict_insert_depth(w,d->branches[ch],depth+1);

    }else{
      dict_insert_depth(w,d->branches[ch],depth+1);
    }
  }
}

/**
 * Check whether a word exists in the dictionary
 * @param w Word to be checked
 * @param d Full dictionary
 * @return If found return 1, otherwise 0
 */
int in_dict(unsigned char *w, Dict *d)
{
  return in_dict_depth(w,d,0);
}

int in_dict_depth(unsigned char *w, Dict *d, int depth)
{
  if(strlen(w)>depth){
    int ch = w[depth];
    if(d->branches[ch]){
      return in_dict_depth(w, d->branches[ch], depth+1);
    }else{
      return 0;
    }
  }else{
    return 1;
  }

}
4

2 に答える 2

3

ルートノードの解放に失敗することを除いて、解放されたコードは問題ないように見えます。

自由度のテストは間違っています。 free変数をに設定しませんNULL。多くの場合、これを明示的に行うことをお勧めします。そのため、すでに解放されているメモリを読み取らないようにしてください。

    free(d->branches[i]);
    d->branches[i] = NULL;   // clobber pointer to freed memory

ルートノードの問題を処理し、おそらくある程度クリーンにするには、次のようにします。

void dict_free(Dict *d)
{
  if(d!=NULL){
    int i;
    for(i=0; i<256; i++){
      if(d->branches[i] != NULL){
        dict_free(d->branches[i]);
        d->branches[i] = NULL;
      }
    }
    free(d);
  }
}
于 2010-09-22T22:39:26.193 に答える
0
dict_free(d->branches[i]);
free(d->branches[i]);
printf("Is it free??  %s\n",d==NULL?"yes":"no");

これはdをチェックしますが、ループ内でdを変更しません。上記でdがnullでないことを確認するので、これは常にnoを出力します。

void dict_free(Dict* d) {
  if (d) {
    for(int i = 0; i < 256; i++) {
      if (d->branches[i]) {
        dict_free(d->branches[i]);
        free(d->branches[i]);

        d->branches[i] = 0;  // mark this branch as freed
        // important if d is reused, and since dict_free doesn't
        // free(d), it could be
      }
    }
  }
}

dを解放しないという既存のコードに従いましたが、Dictが常に同じ方法で割り当てられ(たとえば、dict_new関数を追加)、dict_freeも渡されたオブジェクトを解放するように変更することをお勧めします。

于 2010-09-22T22:45:25.673 に答える