Getting segmentation fault when freeing binary tree recursively [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am working with binary trees in C (Linux Debian, gcc version 4.9.2) and I am having some troubles when freeing memory allocated by malloc. The first deltree() works fine but the second deltree() gives me a segmentation fault. What could be the reason?
#include <stdio.h>
#include <stdlib.h>
/*
compiling with flags -ansi -Wstrict-prototypes
*/
struct treenode{
struct treenode *left;
struct treenode *right;
int data;
};
typedef struct treenode node;
void deltree(node *tree);
int main(void){
node *root;
printf("First tree\n");
printf("===================\n");
root=(node *)malloc(sizeof(node));
root->data=5;
root->left=(node *)malloc(sizeof(node));
root->left->data=4;
root->right=(node *)malloc(sizeof(node));
root->right->data=6;
printf("Root node has data %d\n",root->data);
printf("Left child has data %d\n",root->left->data);
printf("Right child has data %d\n",root->right->data);
deltree(root); /* NO PROBLEM HERE */
printf("Second tree\n");
printf("===================\n");
root=(node *)malloc(sizeof(node));
root->data=-7;
root->left=(node *)malloc(sizeof(node));
root->left->data=-5;
root->right=(node *)malloc(sizeof(node));
root->right->data=-1;
printf("Root node has data %d\n",root->data);
printf("Left child has data %d\n",root->left->data);
printf("Right child has data %d\n",root->right->data);
deltree(root); /* SEGMENTATION FAULT HERE */
printf("Finished\n");
return(EXIT_SUCCESS);
}
void deltree(node *tree){
if(tree!=NULL){
deltree(tree->left);
deltree(tree->right);
printf(".\n");
free(tree);
}
}

You don't initialize the left and right pointers after allocation so their value is undefined.
Either use calloc or set the pointers to NULL manually.

Related

Upon creation of 3 - 5 nodes, segmentation fault is encountered. Why? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I am currently trying to create a phonebook with a linked list. I am focusing first on the insertion function but the problem is that once I create 3 - 5 nodes, onlineGDB shows the error "malloc : corrupted top size", and VS Code shows that I got a segmentation error.
I assume this is an error with the way I am allocating memory. This is the first time that I am working on a structure that contains strings as data instead of integer so I might have missed a thing or two.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
char name[30];
char number[15];
struct node *next;
};
void showMenu();
void insertData(struct node **head, char person[], char phone[]);
void showData(struct node *head);
int main(){
struct node *head = NULL;
char name[30], number[15];
while(1)
{
printf("Name : ");
scanf(" %[^\n]s", name);
printf("Number: ");
scanf(" %[^\n]s", number);
insertData(&head, name, number);
showData(head);
}
return 0;
}
void insertData(struct node **head, char person[], char phone[]){
struct node *new_node = (struct node*) malloc(sizeof(struct node*));
strcpy(new_node->name, person);
strcpy(new_node->number, phone);
new_node->next = *head;
*head = new_node;
}
void showData(struct node *head){
while(head != NULL)
{
printf("%s\t\t%s\n", head->name, head-> number);
head = head->next;
}
printf("\n");
}
Use malloc(sizeof(struct node)) instead of malloc(sizeof(struct node*)) in your function insertData(). You want to allocate the size of the node and not the pointer to node.

segmentation fault while appending a linked-list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to append a node at the end of the linked list and I am getting a segmentation fault. I am not able to figure out where is my mistake. Any Help and suggestions would be appreciated!
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
}*head;
void append(int x)
{
struct node *temp1,*right;
temp1=malloc(sizeof(struct node));
temp1->data=x;
right=malloc(sizeof(struct node));
right=head;
while(right->next != NULL )
right=right->next;
right->next=temp1;
right=temp1;
right->next=NULL;
}
void print(){
struct node *temp=head;
printf("List is: ");
while( temp!=NULL )
{
printf(" %d",temp->data);
temp=temp->next;
}
printf("\n");
}
int main(){
struct node *temp;
int n,i,x;
head=NULL;//empty list;
printf("how many numbers?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("\nEnter the number\n");
scanf("%d",&x)
append(x);
print();
}
}
In your function append you dereference a pointer which points to NULL-
right=malloc(sizeof(struct node));
right=head;
while(right->next != NULL )
....
As head points to NULL and then you point to head by right , so basically by right->next you dereference a pointer to NULL . That's why you maybe getting a seg fault .
And also you allocate memory to right and loose reference to it after making it to point head causing memory leak (avoid such things).
This can be avoided by pointing right after allocating memory by head -
head=right;

Binary tree crashing in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am starting to move into Binary trees in my C class. I understand the concept of a binary tree, but now I'm trying to gain a deeper understanding of how it works. I tried to set up a simple binary tree that changes size based on what the user enters. Whenever I run the program it crashes after the first input. Could someone help me understand why?
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int value;
struct node *left;
struct node *right;
}node;
void traverse(node *root);
void addnode (node *root, int nUser);
int checknode (node *root, int nUser);
int main (void)
{
int nUser;
node *root;
root=(node *)malloc(sizeof(node));
root->value=10;
do
{
printf("Please enter any integer, enter 0 when done\n\n\n"); /*Program crashes when I enter the first value, unsure why*/
scanf("%d",&nUser);
if(!(checknode(root,nUser)))/*check node runs through the binary tree to find the data if it exists, returns 1 if exists, 0 if it doesn't*/
addnode(root,nUser); /*add node runs through the binary tree, when it finds a place where the number will fit, that is a null pointer where the number can be placed it will create a new node with the value and null pointers on right and left*/
}while(nUser);
traverse(root);/*should traverse the tree and print out values*/
return(0);
}
void traverse(node *root)
{
printf("%d/n",root->value);
if(root->left)
{
traverse(root->left);
}
if(root->right)
{
traverse(root->right);
}
}
void addnode (node *root, int nUser)
{
if(root->value<nUser)
if(root->right)
{
addnode(root->right,nUser);
}
else
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->value=nUser;
root->right=temp;
}
if(root->value>nUser)
if(root->left)
{
addnode(root->left,nUser);
}
else
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->value=nUser;
root->left=temp;
}
}
int checknode (node *root, int nUser)
{
if(!(root->value==nUser))
{
if(root->value<nUser)
if(root->right)
{
checknode(root->right,nUser);
}
else
{
return(0);
}
if(root->value>nUser)
if(root->left)
{
checknode(root->left,nUser);
}
else
{
return(0);
}
}
else
{
return (1);
}
}
I think that the problem is that the left and right pointers of root are uninitialized when you pass root to addnode. A buffer returned by malloc is not guaranteed to be NULL.
Try initializing root->right and root->left to NULL before the beginning of the loop.
root=(node *)malloc(sizeof(node));
Change to:
root=(node *)calloc(1, sizeof(node));
You didn't clear root->left and root->right to NULL, so you are using uninitialized pointers. You should change all your malloc to calloc, or you need to clear your left and right pointers to NULL after each malloc.

what is the error in the following lines of c code? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
struct node{
int data;
struct node *next;
};
struct node *head,*temp;
void insert()
{
struct node *var;
head=NULL;
var=(struct node*)malloc(sizeof(struct node));
printf("enter the data:");
scanf("%d",var->data);
temp=head;
if(head==NULL)
{
head=var;
head->next=NULL;
}
else
{
while(temp->next!=NULL)
{
temp=temp->next;
}
if(temp->next==NULL)
{
temp->next=var;
temp=temp->next;
temp->next=NULL;
}
}
}
void display()
{
temp=head;
if(temp==NULL)
{
printf("empty list");
}
while(temp->next!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
}
void main()
{
int value,choice;
printf("\nenter choice:");
scanf("%d",&choice);
while(choice==1)
{
insert();
display();
printf("\nenter choice:");
scanf("%d",&choice);
}
getch();
}
i have made a linklist using c above but the code is not displaying the linklist,instead it shows null pointer compilattion as output,how to solve the problem,i'm new to c coding so cant find adequate solution for this ????
scanf("%d",var->data);
//--> scanf("%d",&(var->data));
scanf's argument must be pointer type.
With every insert, you reset head to NULL. So you will always insert new values at the head and any existing values will be just left in memory, leading to a memory leak.
I guess you want to move the line head=NULL; to the beginning of the main method.
And fix your scanf like keeptalk said.
You seem to be missing to initialise *var's member next after having allocated *var using malloc().

segmentation fault while implementing the binary tree in C [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I got a segmentation fault in the code when I am implementing the binary tree and couldn't figure out why.
#include <stdio.h>
#include <stdlib.h>
struct tree{
int info;
struct tree *lptr,*rptr;
};
typedef struct tree node;
node *create(int, node *);
node *insert(node *);
void preorder(node *);
void inorder(node *);
void postorder(node *);
int main(){
node *root=NULL;
int n,choice=0;
while(choice!=6){
printf("\n\n\t\tMENU");
printf("\n\t1:CREATE\n\t2:INSERTION\n\t3:POSTORDER");
printf("\n\t4:INORDER\n\t5:PREORDER\n\t6:EXIT");
printf("\n\n\tEnter your choice:\t");
scanf("%d",&choice);
switch(choice){
case 1:
printf("\n\tHow many elements to enter\t");
scanf("%d",&n);
root=NULL;
root=create(n,root);
return 0;
}
node *create(int n, node *root){
int i;
for(i=0;i<n;i++)
insert(root);
return root;
}
node *insert(node *root){
int val;
node *temp, *p, *parent;
p=malloc(sizeof(node));
printf("\nEnter data for the node: ");
scanf("%d",&val);
p->info=val;
p->lptr=NULL;
p->rptr=NULL;
if(root=NULL)
root=p;
else{
temp=root;
while(temp){
parent=temp;
if(val<temp->info)
temp=temp->lptr;
if(val>temp->info)
temp=temp->rptr;
if(val==temp->info){
printf("Duplicate data!\n");
free(p);
break;
}
}
if(!temp&&p){
if(val<parent->info) //SEGMENTATION FAULT HERE!!!
parent->lptr=p;
if(val>parent->info)
parent->rptr=p;
}
}
return root;
}
void preorder(node *root){
if(root==NULL)
printf("\n\tEMPTY TREE!\n");
else{
printf("%5d",root->info);
if(root->lptr)
preorder(root->lptr);
if(root->rptr)
preorder(root->rptr);
}
}
void inorder(node *root){
if(root==NULL)
printf("\n\tEMPTY TREE!\n");
else{
if(root->lptr)
inorder(root->lptr);
printf("%5d",root->info);
if(root->rptr)
inorder(root->rptr);
}
}
void postorder(node *root){
if(root==NULL)
printf("\n\tEMPTY TREE!\n");
else{
if(root->lptr)
inorder(root->lptr);
if(root->rptr)
inorder(root->rptr);
printf("%5d",root->info);
}
}
Your problem is on these lines about 10 lines into your insert function:
if(root=NULL)
root=p;
You are assigning root to NULL instead of comparing it to NULL. Then, since NULL evaluates to false, root does not get assigned p. In fact those two lines guarantee that root is NULL after they execute. You just need to add an = to make it a comparison like:
if(root == NULL)
root = p;
This is just an aside, but I recommend putting spaces around your comparison operators. It would make this error much more noticeable, and would make lines like: val>parent->info much more readable, as that line could easily be mistaken for val->parent->info
Edit
As Mark pointed out in the comment below, since == is commutative, but = isn't, you can also avoid this error by switching the order of the operands when you have a value on one side. If you put it on the left like (0 == root) or (NULL == root). The compiler will catch the error for you if you leave an = out since (0 = root) is not syntactically correct.

Resources