我有这段代码,但我中止了(核心转储)。当我对“销毁”行发表评论时,一切都很好,所以我认为错误在那里。有什么想法吗?
#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;
}
答案 0 :(得分: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]
}
^