Possible Duplicate:
Where should I call Free() function?
When I used
“valgrind –leak-check=full –show-reachable=yes ./Main”
to check the memory leak, I had some errors because of not using Free(), but I don’t know where can I use Free() in this method? I need to allocate the memory for new data, if I call free? It means I will delete the data I have put in ??? This is a bit silly:(
In header file
typedef struct TreeNode * Node;
In this .c file:
struct TreeNode {
char* theData;
Node Left;
Node Right;};
This is a recursive function !
Node InsertString(Node tree, char* data) {
if (tree == NULL) {
tree = malloc(sizeof (struct TreeNode));//Error
if (tree == NULL) {
printf("Out of Space!\n");
} else {
tree->theData = malloc(sizeof (char) * strlen(data));//Error
strcpy(tree->theData, data);
tree->Left = tree->Right = NULL;
}
} else {
if (strcmp(data, tree->theData) < 0) {
tree->Left = InsertString(head, tree->Left, data);//Error
} else {
if (strcmp(data, tree->theData) > 0) {
tree->Right = InsertString(head, tree->Right, data);//Error
} else {
printf("This String already Existed\n");
}
}
}
}
return tree;}
And this is how I call this function in another .c file
currentTree = InsearchString(currentTree,"String");
Thank you for reading my post. Happy new Year 😛
The exact problem is because of how you declared your function, specifically with the first parameter. The way you pass
Nodemakes theTreeNodeinstance being passed as anin/outparameter; but the pointer itself is passed by value to the function and is considered aninparameter. Thus, when you attempt to modify the value of the pointer, by callingmalloc, the modified value will not be passed back to the function caller. And since the function caller does not have access to the newly allocated memory, it won’t be able tofreeit, and the memory block will be leaked.Valgrind detects this and warns you properly; however, since it doesn’t know the semantic of your code, it can only tell you that you need to delete the memory block allocated in the function.
The right fix, based on the intended semantic would be to pass
Node *orNode &to the function, which would allow you to manipulate the original value of the pointer, instead of the call stack copy.