I didnt get much help last time I posted this...
please help..
Im having trouble finding what my problem is..
Im writing a binary tree library and when I run this test program: (cannot be changed)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bintree.h"
void print_name(char *key, void *value){
printf("%s\n", key);
}
main(int argc, char *argv[]) {
if (argc <= 1) {
fprintf(stderr, "usage: bst_test name1 name2 ... namek\n");
exit(1);
}
void *tree = create_tree();
int i;
// test inserts
for (i = 1; i < argc; i++) {
tree_insert(strdup(argv[i]), (void *)1, tree);
}
// test print tree
print_tree(tree, print_name);
// test finds
for (i = 0; i < argc; i++) {
if (tree_find(argv[i], tree) == 0)
printf("%s not in data set\n", argv[i]);
}
}
I get these errors:
Code:
(gdb) bt
#0 0xb7edfd2a in strcmp () from /lib/tls/i686/cmov/libc.so.6
#1 0x0804853e in tree_insert (key=0x804a030 "name", value=0x1,
tree=0x804a008) at bintree.c:33
#2 0x0804878d in main (argc=3, argv=0xbfe13134) at test.c:22
Here is the library im writing:
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct _node{
struct _node *children;
struct _node *next;
char *name;
int space;
int x; //x coordinate
int y; //y coordinate
} NODE;
typedef struct _bnode{
char *name;
struct _node family_node;
struct _bnode *left;
struct _bnode *right;
} BNODE;
BNODE *tree_insert(char *key, void *value, void *tree){
BNODE *root = (BNODE *)tree;
if(root == 0){
root = (BNODE *)malloc(sizeof(BNODE));
if(root != NULL)
{
root->name = strdup(key);
root->left = NULL;
root->right = NULL;
}
}else{
if(strcmp(key, root->name) < 0){ <--- line 33
root->left = tree_insert(key, value, root->left);
}else if(strcmp(key, root->name) > 0){
root->right = tree_insert(key, value, root->right);
}else if(strcmp(key, root->name) == 0){
root->name = strdup(key);
}
}
return root;
}
BNODE *tree_find(char *key, void *tree){
BNODE *root = (BNODE *)tree;
if(root == 0){
return 0;
}
if(strcmp(key, root->name) < 0){
return tree_find(key, root->left);
}else if(strcmp(key, root->name) > 0){
return tree_find(key, root->right);
}else{
return root;
}
}
void *create_tree(){
BNODE *new_tree = (BNODE *)malloc(sizeof(BNODE));
new_tree->left = NULL;
new_tree->right = NULL;
return new_tree;
}
void print_tree(void *tree, void(*print_fct)(char *key, void *value)){
BNODE *current = (BNODE *)tree;
if(current == NULL || print_fct == NULL){
return;
}else{
print_tree(current->left, print_fct);
print_fct(current->name, (void *)current->family_node.space);
print_tree(current->right, print_fct);
}
}