I have a binary tree of structs. The struct is
typedef struct hashtag {
char *name;
int acc;
} *Item;
The nodes are organized by the string. I want to print the node which has the highest acc but is first in alphabetical order. My code so far:
Item search_max(link h) {
int max;
char *word;
Item hashtag = (Item)malloc(sizeof(struct hashtag));
Item left = (Item)malloc(sizeof(struct hashtag));
Item right = (Item)malloc(sizeof(struct hashtag));
hashtag = h->item;
max = h->item->acc;
word = h->item->name;
if (h == NULL)
return 0;
left = search_max(h->l);
if (max == left->acc && less(left->name, word))
word = left->name;
if (max < left->acc){
max = left->acc;
word = left->name;
}
right = search_max(h->r);
if (max == right->acc && less(right->name, word))
word = right->name;
if (max < right->acc){
max = right->acc;
word = right->name;
}
hashtag->acc = max;
hashtag->name = word;
return hashtag;
}
h is the head of the tree and less is
#define less(a,b) (strcmp(a,b) < 0)
and link is
typedef struct node{
Item item;
struct node *l;
struct node *r;
} *link;
It gives a segmentation fault(core dumped). Previously I tried the same code without allocating memory for hashtag, left or right (same error).
Item hashtag = (Item)malloc(sizeof(struct hashtag)); Item left = (Item)malloc(sizeof(struct hashtag)); Item right = (Item)malloc(sizeof(struct hashtag)); hashtag = h->item;You are leaking memory here. and :Item search_max(link h) {what is link ? - joop