454,381 Members | 1,640 Online
Need help? Post your question and get tips & solutions from a community of 454,381 IT Pros & Developers. It's quick & easy.

# supposed leak in a recursive algorithm

 P: n/a Good day, Firstly, yes, i am a first year student, and yes, i need help with my home work. But i really want to learn something from it. The task was to find all words in a file that are equal to a certain degree (percentage of first letters). I decided to make a recursive algorithm that is below. It works, and works fast (at least i think so). But i get a feeling that there is a major memory leak. I will really appreciated it, if you point me to it, or point me that there is no such thing. And lastly, excuse me for any misspelling, English is not my native. /* * Recursive search * A sorted list on entry */ list *do_search(list *l, const char percent) { static int pos = 1; /* Symbol position */ static list *found = list_create(); /* result list */ char c, *ref; int i, level; list *n; list_rewind(l); /* Nothing to see here, move along.. */ if(list_getsize(l)<2) return NULL; /* Until which symbol should we go on */ level = list_getmax(l)*percent / 100 ; for(c='a'; c<='z'; c++) { n = list_create(); while((ref = list_next(l)) != NULL){ if (ref[pos-1] == c) { if(level > pos) { /* Still unsatisfactory */ list_add(n,ref); } else { /* We`we already compared sufficient ammount of symbols, so lets push it in result */ list_add(found,ref); } } } pos++; do_search(n, percent); pos--; list_rewind(l); } return found; } The small list manipulation set below. typedef struct list { struct node *first; struct node *last; struct node *cur; unsigned long size; }list; typedef struct node { char *ref; struct node *next; }node; typedef char *str; void util_qsort(str *, int, int); void util_swap(str *, int, int); list *list_create() { list *l = (list *) malloc(sizeof(list)); if(l) { l->last = l->first = l->cur= NULL; l->size = 0; } else { printf("\nMemory error\n"); } return l; } char *list_next(list *l) { node *p; if(p = l->cur) { l->cur = (l->cur)->next; return p->ref; } else return NULL; } void list_rewind(list *l) { l->cur = l->first; } void list_add(list *l, char *ref) { node *p = (node *) malloc(sizeof(node)); if(p) { p->ref = ref; p->next = NULL; if(l->size) { (l->last)->next = p; l->last = p; } else { l->last = l->first = l->cur = p; } l->size++; } else { printf("\nMemory error\n"); } } void list_print(list *l) { node *p = l->first; while(p) { printf("%s \n", p->ref); p = p->next; } } void list_delete(list *l) { node *p = l->first; node *tmp; while(p) { tmp = p; p = tmp->next; free(tmp); } free(l); } list *list_map(str map, int size) { int i; str p; list *l = list_create(); for(i=0, p = map; ifirst; int max = 0, cur; while(p) { cur = strlen(p->ref); if(cur > max) max = cur; p = p->next; } return max; } int list_getsize(list *l) { return l->size; } Dec 28 '05 #1