如何在前缀树中释放内存? (ANSI C)

我试图在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??  %sn",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;
  }

}
    
已邀请:
您的免费代码看起来很好,但它将无法释放根节点。 你对自由的测试是错误的。
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);
  }
}
    
dict_free(d->branches[i]);
free(d->branches[i]);
printf("Is it free??  %sn",d==NULL?"yes":"no");
这会检查d,但您不会在循环中修改d。由于您检查上面的d不为空,因此总是打印否。
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也释放传递的对象。     

要回复问题请先登录注册