Segmentation error in C [closed] - c

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
EDIT: the default for the switch is "invalid option", and i am just trying to create a tree that's all, the program is getting compiled and when i select the option for creating a tree it simply says segmentation error
I've been doing simple data structures programs for the past few days, and the segmentation error is the one bothering me a lot, i researched on the internet about the error and got this link and actually it didn't help.
I'm trying to create a binary search tree. and the return type for create is not void, it struct tree *
program:
struct tree{
int data;
struct tree *rchild, *lchild;
};
struct tree * create(struct tree * root, int d){
if(root==NULL) {
root = (struct tree *) malloc(sizeof(struct tree));
root->data=d;
root->rchild=NULL;
root->lchild=NULL;
}else if(root->data < d) create(root->rchild, d);
else if(root->data > d) create(root->lchild, d);
else if(root->data == d) printf("duplication error");
}
main(){
struct tree *root;
int choice, c;
while(choice!=5){
printf("Enter choice\n1-insert into tree\n5-exit");
scanf("%d", &choice);
switch(choice){
case 1:
printf("enter data to be inserted");
scanf("%d",&c);
printf("error after scanf ");
create(root,c);
break;
case 5: exit(0); default: printf("invalid option");
}
}
}
and the OS i'm using is Backtrack 5 R1
to the one who gave -1: Sir, please tell the answer to my question if it's so silly and non constructive
there is a similar linked list question, I've also answered that question, and I'm writing a tree program by the way.

At least, I do not think the create() can work correctly.
You should use struct tree ** instead of struct tree *.
As your node root is NULL, create(root) means create(NULL), which can not assign the allocated memory to root. You should define it as create(struct tree**), and call it with create(&root)

You are malloc'ing root in the create function, but there is no reason why that survives the call, since it is not being passed by reference. If you passed &root, you could then change *root. As it is, you do not create new nodes in your tree... every time you return from create, the root pointer is NULL...
Alternatively, you could return the new value of root as the return value of the call, and call it with
root = create( root, c);
You can prove this to yourself by adding
printf("root is now %p\n", root);
after your create call...
In short, the following works:
struct tree{
int data;
struct tree *rchild, *lchild;
};
struct tree* create(struct tree * root, int d){
printf("creating node with d = %d\n", d);
if(root==NULL) {
root = (struct tree *) malloc(sizeof(struct tree));
root->data=d;
root->rchild=NULL;
root->lchild=NULL;
}else if(root->data < d) create(root->rchild, d);
else if(root->data > d) create(root->lchild, d);
else if(root->data == d) printf("duplication error");
return root;
}
main(){
struct tree *root;
int choice, c;
while(choice!=5){
printf("Enter choice\n1-insert into tree\n5-exit");
scanf("%d", &choice);
printf("root is now %p\n", root);
switch(choice){
case 1:
printf("enter data to be inserted");
scanf("%d",&c);
printf("made it past scanf\n");
root = create(root,c);
break;
case 5: exit(0);
default: printf("invalid option\n");
}
}
}

Related

C programming: I have an error in creating a binary search tree using 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 5 years ago.
Improve this question
I need to create a c program for BST but I can't create left child or right child for the root node. Creation of root node is ok. I can also search the element in the root node. But Can't add more than one element in the tree
Please help me solve this problem, kindly explain about the mistake that I made
#include<stdio.h>
#include<stdlib.h>
typedef struct tree
{
struct tree *left;
int data;
struct tree *right;
}node;
node *ROOT;
//////////////////////////
void *bud()
{
return (node *)malloc(sizeof(node));
}
/////////////////////
void createNode(int data, node *ptr)
{
if(ptr==NULL)
{
ptr=bud();
ptr->data=data;
ptr->left=NULL;
ptr->right=NULL;
ROOT=ptr;
ptr=NULL;
printf("DONE");
return;
}
else if(data==ptr->data)
{
printf("Duplication not possible");
return;
}
else if (data<ptr->data)
{
//ptr=ptr->left;
createNode(data,ptr->left);
}
else if (data>ptr->data)
{
//ptr=ptr->right;
createNode(data,ptr->right);
}
else
{
printf("INVALID");
}
}
//////////////////////////////////////
void search(int data,node *ptr)
{
if(ptr==NULL)
{
printf("NOT FOUND");
return;
}
else if (ptr->data==data)
{
printf("Item Found");
return;
}
else if(data<ptr->data)
{
//ptr=ptr->left;
search(data,ptr->left);
}
else if (data>ptr->data)
{
//ptr=ptr->right;
search(data,ptr->right);
}
else
{
printf("INVALID");
}
}
/////////////////////////////////
void main()
{
int ch;
ch=0;
while (ch!=6)
{
printf("\nMENU\n1. Create Tree\n2. Search\n3. Inorder\n4.
Preorder\n5. Postorder\n6. Exit\n EnterYour Choice: ");
scanf("%d",&ch);
if(ch==1)
{
int dat;
printf("\nEnter the number to be inserted: ");
scanf("%d",&dat);
createNode(dat,ROOT);
}
else if(ch==2)
{
int dat;
printf("Enter number to be searched: ");
scanf("%d",&dat);
search(dat,ROOT);
}
else if(ch==6)
{
return;
}
else
{
printf("\nEnter a valid choice\n");
}
}
}
The problem is logical error. I can't create the left or right child of the tree. Whatever I insert to the tree gets inserted to the root node.
I can't create the left or right child of the tree. Whatever I insert to the tree gets inserted to the root node.
This is happening because of this statement in your createNode():
ROOT=ptr;
Whenever you are inserting an element in the tree, you are traversing tree recursively and when you find the appropriate location to insert, you are passing it to createNode() which is NULL (either ptr->left or ptr->right) and ROOT is reassigned to ptr.
If I just make changes in your program to make work it properly, the createNode() will look like this:
void createNode(int data, node **ptr)
{
if(*ptr==NULL)
{
*ptr=bud();
(*ptr)->data=data;
(*ptr)->left=NULL;
(*ptr)->right=NULL;
printf("DONE");
return;
}
else if(data==(*ptr)->data)
{
printf("Duplication not possible");
return;
}
else if (data<(*ptr)->data)
{
createNode(data,&((*ptr)->left));
}
else if (data>(*ptr)->data)
{
createNode(data,&((*ptr)->right));
}
else
{
printf("INVALID");
}
}
And in main(), you need to do:
createNode(dat,&ROOT);
However, there is a scope of improvement in your program, for e.g. separate the node creation and insertion operation in your program. I am leaving it up to you to find the improvements and better ways of theirs implementation.
The error is in your createNode() function: you pass node *ptr and assign like this ptr=bud();. But this only modifies local variable, not pointer in parent node. Try passing node **ptr and do dereferencing inside of the function *ptr=bud();. Use & operator to derive pointer to pointer. As #H.S. mentioned ROOT=ptr; statement makes your program lose node. Besides you allocate memory and don't free it (you can't even do that, because you lose pointer to ROOT node).

Binary Search Tree in C.

I am confused that what mistake i am doing. Why isn't it printing the tree in preorder, postorder and inorder. I have written my questions beside the line of code where i am confused. Plus i don't understand how to relate to structs.
#include <stdio.h>
#include<stdlib.h>
typedef struct BST_{
int data;
struct BST_ *lchild, *rchild, *parent;
}BST;
typedef struct BiTree_{
int size;
BST *root; // is it possible to relate this root with the pointer parent of type BST? i yes then how?
}BiTree;;
BST *temp;
BST *createNode(int data){
BST *new_ele;
new_ele=(BST*)malloc(sizeof(BST));
new_ele->data=data;
new_ele->lchild=NULL;
new_ele->rchild=NULL;
new_ele->parent=NULL;
return new_ele;
}
void insertNode(BST *temp,BST *r,int data){
if(temp==NULL){
temp=createNode(data);
}
else if(temp->data >= r->data){
if(r->rchild==NULL){
r->rchild=temp;
}
else{
insertNode(r->rchild,temp,data);
}
}
else if(temp->data <= r->data){
if(r->lchild==NULL){
r->lchild=temp;
}
else{
insertNode(r->lchild,temp,data);
}
}
// return r->data; //why cann't i do this?
}
void preorder(BST *r){
if(r!=NULL){
printf("%d",r->data);
preorder(r->lchild);
preorder(r->rchild);
}
}
void inorder(BST *c){
if(c!=NULL){
inorder(c->lchild);
printf("%d",c->data);
inorder(c->rchild);
}
}
void postorder(BST *r){
if(r!=NULL){
postorder(r->lchild);
postorder(r->rchild);
printf("%d",r->data);
}
}
void delet(BST *r){
if(r!=NULL){
free(r);
}
}
void main(){
BST *new_node,*r=NULL;
BiTree *search;
search=malloc(sizeof(BiTree));
search->root=NULL;
search->size=0;
int i,a,n,data;
printf("Enter the number of element to be inserted\n");
scanf("%d",&n);
printf("Enter the data\n");
for(i=0;i<n;i++){
scanf("%d",&data);
insertNode(temp,r,data);
// printf("Enter the data %d\n",r->data); // unable to print this
search->size++;
}
printf("size is %d\n",search->size);
preorder(r);// why cann't i print the data of r. r is the root of the tree.
postorder(r);
inorder(r);
delet(r);
}
// is it possible to relate this root with the pointer parent of type BST? i yes then how?*
Please rephrase this question
// return r->data; //why cann't i do this?
The signature of the function void insertNode(BST *temp,BST *r,int data){ is saying that nothing should be returned. Change this
printf("Enter the data %d\n",r->data); // unable to print this
In the function r is initialised to NULL and nothing in the function changes this
why cann't i print the data of r. r is the root of the tree.
See the point above
temp is not set to NULL, and I think if its not NULL, it is going to have garbage in it.
With this your insertNode() function will not allocate memory and all the code inside this function is entirely dependent on the garbage value of temp.

C Program to copy one binary search tree to another

So, here i have come up with Binary search tree prgram, where i am creating 2 binary trees tmp and tmp2, where i am trying to copy whole tmp2 to tmp, the node which is taken as input from user. But i am getting some segmentation fault, also i am not so sure if the logic is right.
Here is the whole program, please lemme know where is it going wrong in t_cpy() or please just fix it for me..
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *rlink;
struct node *llink;
}*tmp=NULL,*tmp2=NULL,*tmp3=NULL;
typedef struct node NODE;
NODE *create();
void inorder(NODE *);
void insert(NODE *);
void t_cpy(NODE *,NODE *);
int main()
{
int n,m;
do
{
printf("\n1.create tree 1\n2.Insert element to tree1\n3.create tree 2\n4.Insert element to tree2\n5.Inorder tree1\n6.Inorder tree2\n7.Copy tree2 to tree1\n8.exit\n\n");
printf("\nEnter ur choice: ");
scanf("%d",&m);
switch(m)
{
case 1: tmp=create();
break;
case 2: insert(tmp);
break;
case 3: tmp2=create();
break;
case 4:
insert(tmp2);
break;
case 5: printf("\n\nInorder Tree1: ");
inorder(tmp);
break;
case 6: printf("\n\nInorder Tree 2: ");
inorder(tmp2);
break;
case 7: t_cpy(tmp,tmp2);
break;
case 8: return(0);
}
}while(n!=8);
return(0);
}
void insert(NODE *root)
{
NODE *newnode;
if(root==NULL)
{
newnode=create();
root=newnode;
}
else
{
newnode=create();
while(1)
{
if(newnode->data<root->data)
{
if(root->llink==NULL)
{
root->llink=newnode;
break;
}
root=root->llink;
}
if(newnode->data>root->data)
{
if(root->rlink==NULL)
{
root->rlink=newnode;
break;
}
root=root->rlink;
}
}
}
}
NODE *create()
{
NODE *newnode;
int n;
newnode=(NODE *)malloc(sizeof(NODE));
printf("\n\nEnter the Data ");
scanf("%d",&n);
newnode->data=n;
newnode->llink=NULL;
newnode->rlink=NULL;
return(newnode);
}
void t_cpy(NODE *t1,NODE *t2)
{
int val,opt=0;
NODE *temp;
if(t1==NULL || t2==NULL)
{
printf("Can not copy !\n");
}
inorder(t1);
printf("\nEnter the node value where tree 2 should be copied\n");
scanf("%d",&val);
temp=t1;
while(temp!=NULL)
{
if(val<temp->data)
temp=temp->llink;
else
temp=temp->rlink;
}
if(temp->llink!=NULL || temp->rlink!=NULL)
printf("Not possible to copy tree to this node\n");
else
{
printf("Copy tree to \n 1.Left Node \n 2.Right Node\n Enter your choice : ");
scanf("%d",&opt);
if(opt==1)
{
temp->llink=t2;
}
else if(opt==2)
{
temp->rlink=t2;
}
else
printf("Invalid choice\n");
}
printf("Tree1 after copying is\n");
inorder(temp);
}
void inorder(NODE *tmp)
{
if(tmp!=NULL)
{
inorder(tmp->llink);
printf("%d",tmp->data);
inorder(tmp->rlink);
}
}
EDIT : Thanks to #xaxxon , who helped me with this.
Just update the while to make it work :
while(temp!=NULL&&temp->data!=val)
{
if(val<temp->data)
temp=temp->llink;
else
temp=temp->rlink;
if(temp->llink==NULL && temp->rlink==NULL && temp->data!=val)
{
printf("Invalid Node value entered !\n");
//break;
return 0;
}
and, Now it works fine for if entered value is present in the tree.
Thanks :)
Among other possible problems, you traverse temp until it is null, and on the next line you dereference it.
while(temp!=NULL)
{
if(val<temp->data)
temp=temp->llink;
else
temp=temp->rlink;
}
if(temp->llink!=NULL || temp->rlink!=NULL)
printf("Not possible to copy tree to this node\n");
You most likely mean to break out of this loop if val == temp->data, but you don't. Also, you still need to check to see if temp is null after the loop in case you didn't find val in your tree. Most likely you just meant to say:
if(temp==NULL)
printf("Not possible to copy tree to this node\n");
Also, you can't ask which side of the found node the user wants to copy a tree to. If you have a binary search tree, it has to be the side where the value should go. If you say to copy it to the right side, but all the values are less than the node, it's no longer a BST. In fact, you can't even ask where the value should go and still have a binary search tree. Each node has to be traversed from the root of the tree you want to put the other tree into to maintain the BST mechanics.
When you first use insert(tmp) the value of tmp does not change after you call insert(). Pass the address of tmp to insert(), using a *root within it instead of root.

Error in using Linked List in C program [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 9 years ago.
I am working on an extra credit project for class and here are the specs:
You will write a c program (you should use a design tool but I do not want to see it)
The program will use dynamic memory to create a linked list (NO ARRAYS PERMITTED)
The program will store unlimited number of student records (limited only by RAM).
A student record will consist of Student Name, and Age…you may need to add two additional fields to make this work.
The program will have a way for the user to added records.
The program will have a way for the user to display ALL records (to the screen only, no sort needed).
The program needs a way to quit.
I have all the code finished, but I am getting this pesky error. This is exactly what I see on my computer:
1>linkedProject.obj : error LNK2019: unresolved external symbol _add referenced in function _main
1>E:\Spring 2013\C Programing Class\linkedProject\Debug\linkedProject.exe : fatal error LNK1120: 1 unresolved externals
And here is my code:
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#define pause system ("pause")
// prototype variables
struct node * initnode(char*, int);
void printnode(struct node*);
void printflist(struct node*);
void add(struct node*);
struct node* searchname(struct node*, char*);
struct node{
char name[20];
int age;
struct node *next;
};
struct node *head = (struct node*) NULL;
struct node *end = (struct node*) NULL;
struct node* initnode(char *name, int age){
struct node *ptr;
ptr = (struct node*) calloc(1, sizeof(struct node));
if(ptr == NULL)
return (struct node*) NULL;
else {
strcpy(ptr->name, name);
ptr->age = age;
return ptr;
}
}
void printnode(struct node *ptr) {
printf("Name -> %s\n", ptr->name);
printf("Age -> %d\n", ptr->age);
}
void printlist (struct node *ptr) {
while (ptr != NULL) {
printnode(ptr);
ptr = ptr->next;
}
}
main() {
char name[20];
int age, choice = 1;
struct node *ptr;
while(choice != 3){
system("cls");
printf("1. Add a name\n");
printf("2. List all names\n");
printf("3. Exit");
printf("\nEnter Menu Selection: ");
scanf("%d", &choice);
switch(choice) {
case 1: printf("\nEnter a name: ");
scanf("%s", &name);
printf("Enter age: ");
scanf("%d", &age);
ptr = initnode(name, age);
add (ptr);
break;
case 2: printlist(head);
break;
case 3: exit(3);
default: printf("Invalid Entry");
}// end of switch
}// end of while
}// end of main
All help is greatly appreciated!!
The linker is telling you that it can't find the add function.
You have declared:
void add(struct node*)
in your prototypes, but you haven't defined it anywhere.
You declare add method in prototype. and add(ptr) call in main method. But I cann't see add method definiton. That's why, Compiler rise linker error.

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