我一直在尝试用 C 构建一个优先级队列。
首先,我做一些初始化工作,比如分配空间。
以下是 Initialize 例程,PriorityQueue 是一个指针。
void Initialize(int MaxElement, PriorityQueue H)
{
if (MaxElement < MinPQSize)
printf("Priority queue size is too small");
if (!(H = (PriorityQueue)malloc(sizeof(struct HeapStruct))))
printf("Out of space!!!");
if (!(H->Elements = (ElementType *)malloc((MaxElement+1) * sizeof(ElementType))))
printf("Out of space!!!");
H->Capacity = MaxElement;
H->Size = 0;
H->Elements[0] = MinData;
}
测试代码如下
int MaxElement = 15;
PriorityQueue myHeap;
Initialize(MaxElement, myHeap);
但是当我尝试将元素插入堆中时,会弹出一个段错误。
它可以通过简单地从 Initialize 例程返回 PriorityQueue 指针来解决。
PriorityQueue Initialize(int MaxElement, PriorityQueue H)
{
...
return H;
}
myHeap = Initialize(MaxElement, myHeap);
那么幕后发生了什么?
free() 是在函数没有返回值的情况下返回时调用的吗?
提前致谢!
最佳答案
不,即使您传入的 H
是一个指针,您仍试图在函数内更改它(使用您的第一个 malloc
)。为了改变一些东西,你需要传递一个指向它的指针。在这种情况下,这意味着一个指针指向一个指针:
void Initialize (int MaxElem, PriorityQueue *H) {
if (MaxElem < MinPQSize)
printf("Priority queue size is too small");
if (!(*H = (PriorityQueue)malloc(sizeof(struct HeapStruct))))
printf("Out of space!!!");
if (!((*H)->Elements = (ElemType *)malloc((MaxElem+1) * sizeof(ElemType))))
printf("Out of space!!!");
(*H)->Capacity = MaxElem;
(*H)->Size = 0;
(*H)->Elements[0] = MinData;
}
如果没有额外的间接级别,您在函数内更改的 H
将与函数隔离 - 它不会反射回调用者。
您可能需要考虑的其他几点:
- 您不应该强制转换
malloc
的返回值,它可以隐藏您确实确实想知道的某些错误。 - 如果您的第二个 malloc 失败,您应该释放第一个
malloc
的结果。 - 如果您的任何一个
malloc
调用失败,您应该返回而不是继续,因为如果您取消引用空指针,继续将导致未定义的行为。 - 您可能不想从通用函数打印内容,因为这可能是一种不受欢迎的行为。如果您必须指出问题,最好将指示传回给调用者,让他们以自己的方式处理。
虽然老实说,我实际上喜欢返回值的版本(不需要事先传递它,因为您显然是在创建一个新东西)。应该这样做:
PriorityQueue Initialize (int MaxElem) {
PriorityQueue H;
if (MaxElem < MinPQSize) {
printf("Priority queue size is too small");
return NULL;
}
if (!(H = malloc(sizeof(*H)))) {
printf("Out of space!!!");
return NULL;
}
if (!(H->Elements = malloc((MaxElem+1) * sizeof(ElementType)))) {
printf("Out of space!!!");
free (H);
return NULL;
}
H->Capacity = MaxElem;
H->Size = 0;
H->Elements[0] = MinData;
return H;
}
PriorityQueue myHeap = Initialize (MaxElement);
关于c - 在 C 中动态分配内存时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7342268/