【问题标题】:Run time Error- c project运行时错误 - c 项目
【发布时间】:2017-10-13 13:15:54
【问题描述】:

我创建了一个以非递归方式按级别顺序打印 BTree 的函数。

我有一个问题要找到我的错误..出现以下问题。

运行时检查失败 #2 - 变量“pq”周围的堆栈已损坏。 如果有人能说出问题出在哪里,或者我下次如何自己找到它......? 如果需要,我会添加完整的项目。 enter link description here

void PrintTreeLevelOrder(bstree tree){      //The problem some where here.....
    queue *pq = (queue*)malloc(sizeof(queue)); // is struct of : *front, *rear

    node *current;// is struct of : root
     create_queue(&pq);//create queue- items_num = 0,front = NULL,rear = NULL

     if (tree.root == NULL) {
         printf("Your Tree Is Empty:\n");
         return;
     }
    current = tree.root;
    enqueue(current, &pq); 
    printf("Your Tree Displayed As Queue:\n");
    while ((size_of_queue(&pq) )!=0) {
        current = pq->front;
        printf("%d ", current->data);
        if (current->left != NULL) 
            enqueue(current->left, &pq);

        if (current->right) 
            enqueue(current->right, &pq);
            dequeue(&pq, &current);

    }

}

【问题讨论】:

  • 您以某种方式覆盖了内存,但是您可能这样做的所有功能都没有出现在您的示例中。
  • 请发minimal reproducible example(强调最小)。
  • 我添加了所有函数和数据结构的链接...
  • 提高编译器的警告级别。认真对待编译器的警告并修复代码,直到不再发出警告。不要不要盲目地“抛弃”警告!
  • 对于初学者:这个create_queue(&pq); 看起来不太好。我很确定编译器已经警告过你了。同样在这里:size_of_queue(&pq)

标签: c pointers data-structures


【解决方案1】:

首先我想说你的算法是正确的,请阅读下文。

您的代码有多个需要注意的错误

  • 你以错误的方式使用了 pq 函数,你传递了一个指向指针而不是原始指针的指针,所以你覆盖了代码
  • 除非您将其称为 init,否则应分配 Create_queue,但这不是主要问题
  • 您应该检查 create_queue 是否成功
  • 您将队列中的地址保存为 queue* 为 int,这对于 32 位以外的体系结构是错误的且不可移植
  • 您正在为当前节点(节点树结构)分配一个 queue_element 元素指针结构,这也是不正确的,因为它们是不同的类型和架构

请在这几点上努力,如果您想了解更多详细信息,请与我联系 我很乐意提供帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-06
    • 2016-05-16
    • 2021-06-19
    • 2020-11-16
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多