Cómo cancelar la asignación de memoria en el árbol de prefijo? (ANSI C)
-
04-10-2019 - |
Pregunta
Me trató de liberar memoria en dict_free función (), pero no funciona y no hay por qué hacer. ¿Me estoy perdiendo de algo? No se puede averiguar, lo que está mal.
Editar: Si llamo a free () en dict_free () espero ver que los puntos de puntero a NULL free'd, pero eso no está sucediendo.
Aquí está mi código:
#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;
}
}
Solución
Su código libre se ve bien, excepto que no podrá liberar el nodo raíz.
Su prueba de libre Ness es erróneo. free
no establecerá ninguna variable a NULL
. A menudo es una buena idea para hacer eso de forma explícita, por lo que seguro que no es para leer la memoria ya liberada:
free(d->branches[i]);
d->branches[i] = NULL; // clobber pointer to freed memory
Para manejar el tema nodo raíz, y probablemente un poco más limpio, así, hacer esto:
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);
}
}
Otros consejos
dict_free(d->branches[i]);
free(d->branches[i]);
printf("Is it free?? %s\n",d==NULL?"yes":"no");
Esto comprueba d, pero no modificar d en el bucle. Puesto que usted compruebe que d no es nulo anteriormente, esto no siempre se imprime.
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
}
}
}
}
He seguido su código existente en no liberar d, , pero es posible que desee cambiar las cosas por lo que un diccionario se asigna siempre de la misma manera (por ejemplo, añadir una función dict_new) con dict_free también liberar al objeto pasado.