为什么我得Abort(核心倾倒)

问题描述 投票:0回答:1

我有这段代码,但我得到了Abort(核心转储)。当我评论Destroy线时一切都还可以,所以我认为那里存在错误。有任何想法吗?

#include <stdio.h>
#include <stdlib.h>
#define maxelem 100
#define NIL -1

typedef int BHItem;

struct node {
        BHItem data;
        int priority;
};

typedef struct node *BHNode;

BHNode BHCreate()               //This function creates an empty heap
{
        BHNode heap;
        int i;
        heap=malloc(maxelem*sizeof(struct node));
        for (i=0; i<maxelem; i++) {
                heap[i].data=NIL;
                heap[i].priority=NIL;
        }
}

void BHDestroy(BHNode heap)             //This function destroys a heap
{
        free(heap);
}

int main()
{
        BHNode heap;
        heap=BHCreate();
        BHDestroy(heap);        //Destroy the heap
        return 0;
}
c free
1个回答
4
投票

问题是BHCreate错过了return heap;作为最后声明。它应该如下所示:

BHNode BHCreate()
{
        BHNode heap;
        int i;
        heap=malloc(maxelem*sizeof(struct node));
        for (i=0; i<maxelem; i++) {
                heap[i].data=NIL;
                heap[i].priority=NIL;
        }

        return heap;
}

你应该打开编译器警告来发现这样的事情:

$ gcc main.c -Wall -Wextra
main.c: In function ‘BHCreate’:
main.c:26:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
© www.soinside.com 2019 - 2024. All rights reserved.