插入操作中的分段错误错误

时间:2015-02-02 13:37:49

标签: c segmentation-fault binary-search-tree insertion

我想写一个通用的二叉搜索树。 当我尝试执行插入功能时,我遇到了分段错误。

所以这是(我认为)相关的代码片段:

/* node.h */
typedef struct {
   unsigned int elemSize;
   void *value;
   void *leftChild;    
   void *rightChild;   
   void (*freefn)(void *);     // free function
} Node;

void newNode(Node *node, unsigned int elemSize, void *value) {
    node->elemSize = elemSize;
    node->value = value;
    node->leftChild = NULL;
    node->rightChild = NULL;
}

void nodeSetValue(Node *node, void *value) {
    node->value = value;
}

void nodeSetLeftChild(Node *node, Node *leftChild) {
    node->leftChild = leftChild;
}

/* btree.h */
typedef struct {
    unsigned int elemSize;
    Node *root;                     
    void (*freefn)(void *);         // free function    
    int (*cmpfn)(void *, void *);   // compare function
} Btree;


void btreeInsertHelper(Node *node, void *value, int (*cmpfn)(void *, void *)) {
    if(node == NULL) {
        nodeSetValue(node, value);
        return;
    }
    int cmpresult = cmpfn(value, nodeGetValue(node));
    if(cmpresult >= 0) {
        Node *rightChild = nodeGetRightChild(node);
        if(rightChild == NULL) {
            rightChild = (Node *) malloc(sizeof(Node));
            nodeSetRightChild(node, rightChild);
        }
        btreeInsertHelper(rightChild, value, cmpfn);
    } else {
        Node *leftChild = nodeGetLeftChild(node);
        if(leftChild == NULL) {
            leftChild = (Node *) malloc(sizeof(Node));
            nodeSetLeftChild(node, leftChild);
        }
        btreeInsertHelper(leftChild, value, cmpfn);
    }
    return;
}

void btreeInsert(Btree *btree, void *value) {
    if(btree->root == NULL) {
        Node *root = (Node *) malloc(sizeof(Node));
        newNode(root, sizeof(btree->elemSize), value);
        btree->root = root;
        return;
     } else {
        btreeInsertHelper(btree->root, value, btree->cmpfn);
        return;
   }
}

/* test.c */
int intCmp(void *a, void *b) {
    return *(int *)a - *(int *)b;
}

int main() {

    Btree btree;
    newBtree(&btree, sizeof(int), NULL, intCmp);

    int a = 10;
    int b = 9;
    int c = 11;
    int d = 3;

    btreeInsert(&btree, &a);
    btreeInsert(&btree, &b);
    btreeInsert(&btree, &c);
    btreeInsert(&btree, &d);

    return 0;
}

我感觉我在某些方面传递了错误的引用

1 个答案:

答案 0 :(得分:0)

我为我的工作使用了一个简单的编辑器。 现在,在安装IDE并调试我的程序之后,我发现在btreeInsertHelper函数的开头节点'永远不会变成NULL。相反,我必须检查node->值是否为NULL。在跳过if子句后,比较函数比较了' value'为NULL值。

感谢您的帮助。为了完整起见,我的newBtree函数:

void newBtree(Btree *btree, unsigned int elemSize, void(freefn (void*),int(cmpfn)(void *,void *)) {
    btree->elemSize = elemSize;
    btree->freefn = freefn;
    btree->cmpfn = cmpfn;
    btree->root = NULL;
}