【问题标题】:SegFault when passing functions in C在 C 中传递函数时出现 SegFault
【发布时间】:2015-02-22 18:08:09
【问题描述】:

当通过几个结构传递函数指针时,我遇到了 SegFault,我不知道我做错了什么。代码如下:

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。我有一种感觉,我只是没有在我应该在的地方传递一个指针,但我就是找不到它。

【问题讨论】:

  • list-&gt;root 是什么东西?您发布的struct 没有root 作为成员。
  • SLInsert() 不会使用正确数量的参数调用 afl_insert()。当修复它以便编译时,一切似乎都没有段错误。
  • 是的,我的头文件没有我的更新版本,所以它没有给我一个错误。一旦我发布了我注意到的完整代码

标签: c function struct function-pointers


【解决方案1】:

错误是您拨打malloc

 SortedListPtr slp = malloc(sizeof(SortedListPtr));

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

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

【讨论】:

  • 我仍然在同一行遇到段错误。我不需要 malloc 比较函数,不是吗(因为它是一个指针)?
  • 不能复制:ideone.com/BtZ1vh 另外,不需要malloc函数指针。您正在分配现有函数的地址,所以没有问题。
  • 如果无法复制,我应该如何调试?有什么建议吗?
  • @JeremyRosenberg:发布您的真实代码将是一个有用的起点。发布假代码浪费大家的时间。
  • 会做,但抽象到问题上可以节省每个人的时间。除非我当然误解了这个问题哈哈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
相关资源
最近更新 更多