我试图在dict_free()函数中处理内存,但是它不起作用,我不为什么。我想念什么吗?不知道,怎么了。

编辑:如果我在dict_free()中拨打free(),我希望可以看到免费指针指向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;
  }

}
有帮助吗?

解决方案

您的免费代码看起来不错,除了它将无法释放根节点。

您的自由度测试是错误的。 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??  %s\n",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函数),并释放传递的对象。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top