Not able to free memory from function - c

I have a C program that implements trees. my cleanup function looks like this:
void cleanup_tree( TreeNode* root ){
printf("Called\n");
if(root->left!=NULL){
cleanup_tree(root->left);
}
if(root->right!= NULL){
cleanup_tree(root->right);
}
if(root->right==NULL &&root->left==NULL) {
/*free(root);*/
free(root->word);
free(root);
root = NULL;
}
}
My Tree struct has
typedef struct TreeNode_st {
char *word; // the word held in this node
unsigned int frequency; // how many times it has been seen
struct TreeNode_st *left; // node's left child
struct TreeNode_st *right; // node's right child
} TreeNode;
I am initialising a tree like this :
TreeNode* initTreeNode(){
TreeNode *mainNode= (TreeNode*)malloc(sizeof(TreeNode));
mainNode->frequency = 0 ;
mainNode->word = NULL;
mainNode->left = NULL;
mainNode->right = NULL;
return mainNode;
}
in my main, I have called
TreeNode *mainNode =initTreeNode();
and I'm doing operations on it , and just before program exit, i called
cleanup_tree(mainNode);
Valgrind reported memory leaks, so just to test , i did
I put
printf("~~~FINAL NULL TEST %s",mainNode->left->right->word);
below my cleanup_tree line,
And i'm able to see the word even now.
What am I doing wrong ?

There are two ways:
You pass it a pointer-to-a-pointer: void cleanup_tree( TreeNode **root)
You set the fields to NULL after the cleanup returns:
Currently, the changes made by the function are not reflected in the node parameter you passed.
Ad 2:
cleanup_tree(root->right);
root->right= NULL;

You seem to be under the impression that setting root = NULL at the end of this function will be visible in the calling function so that the third if block gets called. That's not the case.
You want to always free() the word as well as the node itself.
void cleanup_tree( TreeNode* root ){
printf("Called\n");
if(root->left!=NULL){
cleanup_tree(root->left);
}
if(root->right!= NULL){
cleanup_tree(root->right);
}
free(root->word);
free(root);
}

Related

SIGSEGV on access to pointer to left node of binary tree, even though the pointer is initialized

I am trying to create a function which returns the mirrored copy of a binary tree.
By "mirrored" I mean a tree with each left node as its right node and vice versa.
The one on the left gets copied to resemble the one on the right. This is the code of the function, with the definition of the binary nodes and "insert node" function that I use:
typedef struct bNode {
int data;
struct bNode *left;
struct bNode *right;
} bNode;
// =============================================================
bNode* reverse_tree (bNode **tree) {
bNode *copy = malloc(sizeof(bNode));
copy->data = (*tree)->data;
if (!((*tree)->right) && !((*tree)->left)){
return copy;
}
copy->left = reverse_tree(&(*tree)->right);
copy->right = reverse_tree(&(*tree)->left);
return copy;
}
// =============================================================
void insert(bNode **tree, int data) {
bNode *temp, *previous, *current;
if (*tree == NULL) {
temp = (bNode *) malloc(sizeof (bNode));
temp->data = data;
temp->left = NULL;
temp->right = NULL;
*tree = temp;
return;
}
if (data < (*tree)->data) {
insert(&(*tree)->left, data);
} else if (data > (*tree)->data) {
insert(&(*tree)->right, data);
}
}
After some troubleshooting, one single layer of recursion works fine, but after that, the pointers break (that is, they point to an inaccessible part of memory), and the program receives a SIGSEGV Segmentation fault.
Why do I receive this SIGSEGV and how do I avoid it?
P.S I am quite inexperienced with pointers; I hope it's not too bad.
(The one on the left gets copied to resemble the one on the right)
At least the function reverse_tree has a bug.
The sub-statement of this if statement:
if (!((*tree)->right) && !((*tree)->left)){
return copy;
}
gets the control when the both pointers, right and left, are null pointers.
So this code snippet:
copy->left = reverse_tree(&(*tree)->right);
copy->right = reverse_tree(&(*tree)->left);
can get the control when only one of the pointers is a null pointer.
In this case in the next recursive call of the function this statement:
copy->data = (*tree)->data;
invokes undefined behavior for the passed null pointer.

Unable to print elements in binary search tree

My code is not printing the elements of binary search tree:
//x is the element to be inserted
//structure of program
typedef struct BST
{
int info;
struct BST *left;
//pointer to left node
struct BST *right;
//pointer to right node
}
bst;
//global root variable
bst *root;
void insert(int x)
{
bst *ptr,*sptr=root;
ptr=(bst*)malloc(sizeof(bst));
ptr->info=x;
if(root==NULL)
{
ptr->left=ptr->right=NULL;
root=ptr;
}
while(sptr!=NULL)
{
if(x<sptr->info)
{
sptr=sptr->left;
}
else
sptr=sptr->right;
}
sptr=ptr;
}
edit:
//following is the show function
void show()
{
bst *ptr=root;
while(ptr!=NULL)
{
//it will print untill the ptr is null
printf("%d",ptr->info);
ptr=ptr->left;
ptr=ptr->right;
}
}
Where is the value of root coming from? You're not passing in the value anywhere? Also, it is tough to help when we don't know the design of type bst.
It appears that you have the right idea. Create a node, and give it some data. If the root is null, then the new value is the root of the BST. After that you go ahead and find the first null node either in the left or right subtree of the root using the standard BST behavior. Finally, when you reach the end you go ahead and insert the last node in the proper place.
void insert(int x)
{
bst *ptr, *sptr=root; //<-- the value right here?
ptr = malloc(sizeof(bst));
ptr->info = x;
if(root == NULL)
{
ptr->left=ptr->right=NULL;
root=ptr;
}
while(sptr!=NULL)
{
if(x<sptr->info)
{
sptr=sptr->left;
}
else
sptr=sptr->right;
}
sptr=ptr; // <-- What is this line trying to do?
}
However, where did your updated tree go?
Since in C everything is passed by value, you're running into the problem where you're not seeing your updated tree after you leave this function. You need to go ahead and change the function to return a bst* type, and also maintain the root node during the entire function. Now the first line of code (*sptr = root) makes more sense! Finally, you were not setting the left and right fields of ptr to NULL. This means you were jumping over your if statements.
bst* insert(int x, bst *root)
{
bst *ptr, *sptr=root;
ptr = malloc(sizeof(bst));
ptr->left = NULL;
ptr->right = NULL;
ptr->info = x;
if(root == NULL)
{
ptr->left=ptr->right=NULL;
root=ptr;
return root;
}
while(sptr!=NULL)
{
if(x<sptr->info)
{
sptr=sptr->left;
}
else
sptr=sptr->right;
}
sptr=ptr;
return root;
}
What about the next function?
I just started looking at this one too. I am not used to the global variables in c, so I will go ahead and make two modifications. Let's make this recursive, and pass in the value of the root rather than using the global.
void show(bst *root)
{
if(root == NULL){
return;
}
printf("%d",root->info);
show(root->left);
show(root->right);
}
This will take in some value, and solve the tree recursively, and print as it reaches each node. Thus, it will print the root node (if it exists), and then print the left entire left subtree before it prints the right subtree.
Finally, looking at your main
I added the local variable root and thus you will have to remove the global variable named root outside of your main function. I also set the value of it to null so your first insert will fire correctly.
int main()
{
int i,n,x;
bst *root = NULL; //<-- I added this line of code to remove the global
puts("Enter number of elements");
scanf("%d",&x);
for(i=0;i<x;i++)
{
puts("Enter elements");
scanf("%d",&n);
root = insert(n, root);
}
show(root);
return 0;
}
I hope this helps!

Original node changes when inserting nodes into binary tree

I'm trying to make a binary tree using a recursive insert function but my root node seems to keep changing(if it didn't, printf should always give the same output in the code below). Any thoughts on how to fix this?
typedef struct Tnode{
char name[30];
int value;
struct Tnode *left;
struct Tnode *right;
} Tnode;
Tnode *insert(Tnode *node, char *name, int value){
if(node==NULL){
Tnode *temp = malloc(sizeof(struct Tnode));
sprintf(temp->name,"%s",name);
temp->value = value;
temp->left = NULL;
temp->right = NULL;
return temp;
}
else if(strcmp(name,node->name)<0)
{
node->left = insert(node->left, name, value);
}
else if(strcmp(name,node->name)>0)
{
node->right = insert(node->right, name, value);
}
else{
printf("something went wrong\n");
}
}
int main(){
Tnode *root = NULL;
root = insert(root,"george",11);
root = insert(root,"dick",12);
printf("%s\n",root->name);
root = insert(root,"walter",13);
root = insert(root,"harry",13);
printf("%s\n",root->name);
root = insert(root,"zink",40);
printf("%s\n",root->name);
}
ok, so now we've figured it out together. your insert() is declared as
Tnode *insert(...)
so it allways needs to return a pointer to a Tnode, but there are cases in your if-clause that lead to an execution branch that doesn't return anything. I guess it's undefined what will be the return value.
Since insert() operates recursively by passing the call "if you're a leaf, put the value here and return yourself", you need to handle the case "and if you're not, do ... and return ...". So imagine you already have a large tree and you insert a value, the root passes the call down the binary structure until the correct position is found. The final call (where the recursion ends) will return a *Tnode to that leaf so that the previous call can correctly set node->left = insert(...);, but there are still "open" calls on the stack (since it's a recursion) that needs to get closed, i.e. the function terminates and every node writes something into node->left or node->right. If you don't return anything, there might be some arbitrary values that break your data structure and lead to undefined behavior.
So, the solution was just to add a return node; at the end so that the recursive calls can be finalized by leaving the "passing" nodes between the root and the new leaf unchanged.

Linked list loops endlessly

I'm writing a simple linked list implementation for the sake of learning. My linked list consists of node structures that contain an int value and a pointer to the next node. When I run my code, it loops endlessly even though it should terminate when it reaches a NULL pointer. What am I doing wrong?
#include <stdio.h>
struct node {
int value;
struct node *next_node;
};
struct node * add_node(struct node *parent, int value)
{
struct node child;
child.value = value;
child.next_node = NULL;
parent->next_node = &child;
return parent->next_node;
}
void print_all(struct node *root)
{
struct node *current = root;
while (current != NULL) {
printf("%d\n", current->value);
sleep(1);
current = current->next_node;
}
}
int main()
{
struct node root;
root.value = 3;
struct node *one;
one = add_node(&root, 5);
print_all(&root);
}
Your program exhibits undefined behavior: you are setting a pointer to a locally allocated struct here:
struct node child;
child.value = value;
child.next_node = NULL;
parent->next_node = &child;
return parent->next_node;
Since child is on the stack, returning a parent pointing to it leads to undefined behavior.
You need to allocate child dynamically to make it work:
struct node *pchild = malloc(sizeof(struct node));
// In production code you check malloc result here...
pchild->value = value;
pchild->next_node = NULL;
parent->next_node = pchild;
return parent->next_node;
Now that you have dynamically allocated memory, do not forget to call free on each of the dynamically allocated nodes of your linked list to prevent memory leaks.
add_node returns a pointer to a local variable which immediately goes out of scope and may be reused by other functions. Attempting to access this in print_all results in undefined behaviour. In your case, it appears the address is reused by the current pointer, leaving root->next_node pointing to root.
To fix this, you should allocate memory for the new node in add_node
struct node * add_node(struct node *parent, int value)
{
struct node* child = malloc(sizeof(*child));
if (child == NULL) {
return NULL;
}
child->value = value;
child->next_node = NULL;
parent->next_node = child;
return child;
}
Since this allocates memory dynamically, you'll need to call free later. Remember not to try to free root unless you change it to be allocated using malloc too.

Maintaining chain of pointers to address

This is something of a followup to a question I asked earlier. I'm still learning my way around pointers, and I'm finding it difficult to maintain a reference to the physical address of a struct while iterating through a data structure. For example, I have a simple, barebones linked list that I'd like to delete from via a searching pointer:
struct Node{
int value;
struct Node* next;
};
struct Node* createNode(int value){
struct Node* newNode = malloc(sizeof *newNode);
newNode->value = value;
newNode->next = NULL;
return newNode;
}
void nodeDelete(Node **killptr){
free(*killptr);
*killptr = NULL;
}
int main(){
struct Node* head = createNode(16);
head->next = createNode(25);
head->next->next = createNode(51);
head->next->next->next = createNode(5);
// Working code to delete a specific node with direct reference address
struct Node** killptr = &head->next;
nodeDelete(killptr);
return 0;
}
The above shows deleting by passing nodeDelete a pointer to the address of the head pointer. What I want to do is be able to move my pointer ->next until it finds something that satisfies a delete condition, and call nodeDelete on that. I've tried the following:
struct Node* searchAndDestroy = head;
while(searchAndDestroy->value != NULL){ // Search until the end of the structure
if (searchAndDestroy->value == 25){ // If the value == 25
nodeDelete(&searchAndDestroy); // Delete the node (FAILS: Nullifies the
// address of search variable, not the
break; // original node)
}else{
searchAndDestroy = searchAndDestroy->next;
}
}
I've also tried something along the lines of:
if (searchAndDestroy->value == 25){
struct Node** killptr = (Node**)searchAndDestroy);
nodeDelete(killptr); // Still fails
}
I need to be able to move my pointer to the ->next point, but also maintain a reference to the address of the node I want to delete (instead of a reference to the address of the search node itself).
EDIT: Some clarification: I realize that deleting from a linked list in this fashion is naive, leaks memory, and drops half the list improperly. The point is not to actually delete from a linked list. Ultimately the idea is to use it to delete the leaves of a binary search tree recursively. I just figured a linked list would be shorter to portray in the question as an example.
struct Node **searchAndDestroy;
for (searchAndDestroy = &head;*searchAndDestroy; searchAndDestroy = &(*searchAndDestroy)->next ){
if ((*searchAndDestroy)->value == 25){
nodeDelete(searchAndDestroy); // Function should be changed to assign the ->next pointer to the **pointer
break;
}
}
And change nodeDelete like this:
void nodeDelete(Node **killptr){
Node *sav;
if (!*killptr) return;
sav = (*killptr)->next;
free(*killptr);
*killptr = sav;
}
Unless I'm missing something, your nodeDelete function is working as designed, but you want to keep a way of accessing the next node in the chain. The easiest way of doing this is just to add a temporary variable:
struct Node *searchAndDestroy = head, *temp = NULL;
while(searchAndDestroy != NULL){ // Need to check if the node itself is null before
// dereferencing it to find 'value'
temp = searchAndDestroy->next;
if (searchAndDestroy->value == 25){
nodeDelete(&searchAndDestroy);
break;
}else{
searchAndDestroy = temp;
}
}
if you give the Address of the previous Node that is where the link to deleting node present then it is very simple
code snippet for that:-
void delete_direct (struct Node *prevNode)
{/*delete node but restrict this function to modify head .So except first node use this function*/
struct Node *temp;/*used for free the deleted memory*/
temp=prevNode->link;
prevNode->link=temp->link;
free(temp);
}
struct Node * find_prev(struct Node *trv_ptr,int ele)
{
/*if deleting element found at first node spl operation must be done*/
if(trv_ptr->data==ele)
return trv_ptr;
while((trv_ptr->link)&&(trv_ptr->link->data!=ele))
{
trv_ptr=trv_ptr->link;
}
if(trv_ptr->link==NULL)
{
return NULL;
}
else
return trv_ptr;
}
main()
{
/*finding Node by providing data*/
struct Node *d_link;
struct Node *temp;
d_link=find_prev(head,51);
if(d_link==NULL)
{//data ele not present in your list
printf("\nNOT FOUND\n");
}
else if(d_link==head)
{//found at first node so head is going to change
temp=head;
head=head->link;
free(temp)
}
else
{//other wise found in some where else so pass to function
delete_direct (d_link);
}
}

Resources