为什么我会中止(核心已转储)
Why do I get Abort (core dumped)
我有这段代码,但我得到了 Abort(core dumped)。当我评论 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;
}
问题是 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]
}
^
我有这段代码,但我得到了 Abort(core dumped)。当我评论 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;
}
问题是 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]
}
^