c - 在 C 中动态分配内存时出现段错误

标签 c

我一直在尝试用 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/

相关文章:

c - 理解宏扩展规则的问题

c - 内核模块无法在某个语句之后执行语句

c - 两个带有 void 和空参数列表的函数声明

c - Lex:多个文件,不同的规则

c - 静态变量存储说明

c++ - 如何使用 MPI 在多个独立启动的程序之间传输数据

c - 如何在 C 中创建和打开一个文件并使其对整个程序可用?

c - 为什么指针值被用作 .而不是 -> 在此

c - 如何使用双向链表正确初始化大结构?

c - 文件的读取和写入只有在程序完成后才能完成