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.
Related
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.
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.
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.
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");
}
}
}
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 10 years ago.
Please let me know what's wrong with this code, wherein I have added some nodes at the beginning and then displayed them,which are further tried to sort, but I'm not getting the sorted result...
thank you :)
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
struct node
{
int data;
struct node *link;
};
void append(struct node **q,int num)
{
struct node *temp;
temp=malloc(sizeof(struct node));
temp->data=num;
temp->link=*q;
*q=temp;
}
void display(struct node *q)
{ struct node *temp;
temp=q;
printf("\n");
while(q!=NULL)
{
printf(" %d",q->data);
q=q->link;
}
q=temp;
}
void sort(struct node *q)
{
struct node *temp1, *temp2; int i,j,temp3;
temp1=q;
temp2=q->link;
for(i=0;i<6;i++)
{
for(j=0;j<6-i;j++)
{
if(temp1->data>temp2->data)
{
temp3=temp1->data;
temp1->data=temp2->data;
temp2->data=temp3;
}
temp2=temp2->link;
}
temp1=temp1->link;
temp2=temp1->link;
}
}
void main()
{
struct node *p;
p=NULL;
append(&p,7);
append(&p,5);
append(&p,9);
append(&p,2);
append(&p,8);
display(p);
sort(p);
display(p);
}
I did not try to follow the entire logic, but your problem is you're dereferencing NULL pointers:
cristi:tmp diciu$ gdb ./a.out
GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Mon Aug 8 20:32:45 UTC 2011)
[..]
(gdb) r
Starting program: /private/tmp/a.out
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x0000000100000d68 in sort (q=0x100100970) at test.c:44
44 if(temp1->data > temp2->data)
(gdb) p temp1
$1 = (struct node *) 0x100100970
(gdb) p temp2
$2 = (struct node *) 0x0
A hackish fix (I did not follow the code's logic so I'm not sure this is correct) is to avoid dereferencing NULL pointers:
void sort(struct node *q)
{
struct node *temp1, *temp2; int i,j,temp3;
temp1=q;
temp2=q->link;
for(i=0;i<6;i++)
{
if(temp1==NULL || temp2==NULL)
continue;
for(j=0;j<6-i;j++)
{
if(temp2 == NULL)
continue;
if(temp1->data > temp2->data)
{
temp3=temp1->data;
[..]
The correct fix is to properly walk the list (you seem to assume the list has 6 elements when you can walk the list until you hit the NULL element since that is the end of the list).