gpt4 book ai didi

c - 在 C 中传递函数时出现 SegFault

转载 作者:行者123 更新时间:2023-11-30 15:23:45 25 4
gpt4 key购买 nike

当通过几个结构传递函数指针时,我遇到了 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。我有一种感觉,我只是没有将指针传递到应该在的位置,但我就是找不到它。

最佳答案

错误是您对 malloc 的调用:

 SortedListPtr slp = malloc(sizeof(SortedListPtr));

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

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

关于c - 在 C 中传递函数时出现 SegFault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28661336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com