在 C 中传递函数时出现段错误

SegFault when passing functions in C

我在通过几个结构传递函数指针时遇到了段错误,我不知道自己做错了什么。这是代码:

typedef int (*CompareFuncT)( void *, void * );
typedef void (*DestructFuncT)( void * );

struct AVL
{
    void * obj;

    struct AVL * parent;
    struct AVL * leftChild;
    struct AVL * rightChild;
};
typedef struct AVL * AVLPtr;

struct SortedList
{
    AVLPtr root;
    CompareFuncT comp;
    DestructFuncT dest;
};
typedef struct SortedList * SortedListPtr;

SortedListPtr SLCreate(CompareFuncT cf, DestructFuncT df){
    SortedListPtr slp = malloc(sizeof(struct SortedList));
    if(slp == NULL){
        printf("Not enough space for list\n");
        return NULL;
    }

    slp->root = NULL;
    slp->comp = cf;
    slp->dest = df;

    return slp;
}

AVLPtr avl_insert(AVLPtr root, AVLPtr parent, void * obj, int (*compare)(     void *, void * )){

    int s = 5;
    int k = 6;
    compare(&s, &k);
    if(root == NULL){
        root = malloc(sizeof(struct AVL));
        if(root == NULL){
            printf ("Out of memory - creating AVL node\n");
            return NULL;
        }

        root->obj = obj;
        root->parent = parent;
        root->leftChild = NULL;
        root->rightChild = NULL;
        return root;
    }

    else if (compare(obj, root->obj) < 0){

        root->leftChild = avl_insert(root->leftChild, root, obj, compare);
        root = balance(root);
    }

    else if (compare(obj, root->obj) >= 0){
        root->rightChild = avl_insert(root->rightChild, root, obj, compare);
        root = balance(root);
    }

    return root;
}

int SLInsert(SortedListPtr list, void * newObj){
    list->root = avl_insert(list->root, newObj, list->comp);
    if(list->root == NULL)
        return 0;
    return 1;
}


int compareInts(void *p1, void *p2)
{
    int i1 = *(int*)p1;
    int i2 = *(int*)p2;

    return i1 - i2;
}

void destroyBasicTypeNoAlloc(void *p) {
    return;
}

int main(int argc, char **argv) {
    int s = 9;

    SortedListPtr list = SLCreate(compareInts, destroyBasicTypeNoAlloc);

    SLInsert(list, &s);


    return 0;

}

显然有更多的参数通过函数,但这是我的比较函数的传播。我在 avl_insert 的比较中遇到了 SegFault。我有一种感觉,我只是没有将指针传递到我应该传递的位置,但我就是找不到它。

错误是你调用malloc:

 SortedListPtr slp = malloc(sizeof(SortedListPtr));

您分配的是指针占用的字节数,这是不正确的。应该是:

 SortedListPtr slp = malloc(sizeof(struct SortedList));