How can I fix the memory leak in talloc()?
edit:
I followed the backtrace and I freed root. However, I'm having the same trouble in strdup now. Do I have to free that *p? but how?
Code:
valgrind --tool=memcheck --leak-check=full ./binarytree
==2532== Memcheck, a memory error detector
==2532== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==2532== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==2532== Command: ./binarytree
==2532==
void void void
3 void
==2532==
==2532== HEAP SUMMARY:
==2532== in use at exit: 37 bytes in 2 blocks
==2532== total heap usage: 2 allocs, 0 frees, 37 bytes allocated
==2532==
==2532== 37 (32 direct, 5 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==2532== at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2532== by 0x400A80: talloc (binarytree.c:86)
==2532== by 0x4009B4: addtree (binarytree.c:67)
==2532== by 0x400844: main (binarytree.c:29)
==2532==
==2532== LEAK SUMMARY:
==2532== definitely lost: 32 bytes in 1 blocks
==2532== indirectly lost: 5 bytes in 1 blocks
==2532== possibly lost: 0 bytes in 0 blocks
==2532== still reachable: 0 bytes in 0 blocks
==2532== suppressed: 0 bytes in 0 blocks
==2532==
==2532== For counts of detected and suppressed errors, rerun with: -v
==2532== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)
Code:
struct tnode {
char* word;
int count;
struct tnode *left;
struct tnode *right;
};
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXWORD 100
struct tnode *addtree(struct tnode *, char *);
void treeprint(struct tnode *);
int getword(char *, int);
struct tnode *talloc(void);
char *Strdup(char *);
int main(void)
{
struct tnode *root;
char word[MAXWORD];
root = NULL;
while(getword(word,MAXWORD)!= EOF)
if(isalpha(word[0]) )
root = addtree(root, word);
treeprint(root);
return 0;
}
char buffer[MAXWORD];
int bp = 0;
int getword(char *word, int lim)
{
char *w = word;
int c;
while(isspace(c = getc(stdin)) )
;
if(c != EOF)
*w++ = c;
if(!isalpha(c))
{
*w = '\0';
return c;
}
for(; --lim > 0; w++)
if(!isalnum(*w = getc(stdin)) )
{
ungetc(*w, stdin);
break;
}
*w = '\0';
return word[0];
}
struct tnode *addtree(struct tnode *p, char *w)
{
int cond;
if(p == NULL)
{
p = talloc();
p->word = Strdup(w);
p->count = 1;
p->left = p->right = NULL;
}
else if( (cond = strcmp(w, p->word) ) == 0)
p->count++;
else if(cond < 0)
p->left = addtree(p->left, w);
else
p->right = addtree(p->right, w);
return p;
}
#include <stdlib.h>
struct tnode *talloc(void)
{
return (struct tnode *) malloc(sizeof(struct tnode) );
}
char *Strdup(char *s)
{
char *p;
p = (char *) malloc(strlen(s)+1);
if(p != NULL)
strcpy(p,s);
return p;
}
void treeprint(struct tnode *p)
{
if(p != NULL)
{
treeprint(p->left);
printf("%4d %s\n", p->count, p->word);
treeprint(p->right);
}
}