
Memory leak in a linked list.
Hello,
I have code (condensed version included below) that works very
well, except for memory leaks! Oxymoron? I've included only the input
and output portions of my code because I believe this is where the error
resides. Because of the input()ing process, the program takes up ten
times the size of the input and nothing seems to be freed until the
program terminates. I think it's a case of locally malloc()d and
declared variables being returned. But I submit this situation to the
think tank of comp.lang.c..
// It uses a linked-list..
struct node {
char *entry;
struct node *link;
Quote:
};
//Application: headNode = input(headNode, string);
//..where 'string' is a NULL terminated array of characters.
struct node * input(struct node * headNode, char *input) {
int length;
struct node *newNode;
newNode = (struct node *) malloc(sizeof(struct node));
length = strlen(input)+1;
newNode->entry = malloc(length);
memcpy(newNode->entry, input, length);
newNode->link = headNode;
// The new headNode should be assigned directly?
return newNode;
Quote:
}
//Application: output(headNode);
void output(struct node * headNode) {
struct node *currNode;
struct node *tmpNode;
currNode = headNode;
while(currNode != NULL) {
printf("%s\n", currNode->entry);
tmpNode = currNode;
currNode = currNode->link;
/*At this point the memory is effectively freed, however
the amount of memory consumed by the program isn't reduced. I assume
this is one of the wonders of Windows NT, where it decides to keep the
freed memory for future calls to malloc()?*/
//free((char *)tmpNode->entry);
free((struct node *)tmpNode);
}
Quote:
}
Thanks,
Daniel Tremblay