c++编程错误-运行时错误

C++ programming errror - Run time error

本文关键字:运行时错误 错误 编程 c++      更新时间:2023-10-16

在执行下面的c++代码时出现了运行时错误。有人能帮我解释一下为什么我得到这个运行时错误吗?

#include<iostream>
using namespace std;
struct node
{
   int data;
   struct node *left;
   struct node *right;
   struct node *rlink;
};
struct qnode
{
   struct node *lnode;
   int level;
};
struct node* newnode (int n)
{
   struct node *temp;
   temp= new struct node;
   temp->data=n;
   temp->left=NULL;
   temp->right=NULL;
   temp->rlink=NULL;
   return temp;
}
void link (struct node *n, int level)
{
  struct qnode *qn;
  struct qnode *current, *next;
  struct qnode nextd;
  next = &nextd;
  (next->lnode)->data=5;
  cout << (next->lnode)->data << endl;
}

int main()
{
    struct node *root = newnode(10);
    root->left        = newnode(8);
    root->right       = newnode(2);
    root->left->left  = newnode(3);

    link (root, 0);
    return 0;

  }

在您的link函数中,您这样做了:

next = &nextd;

nextd未初始化,并且在将其地址分配给next时包含垃圾值。接下来的行尝试访问它,这会导致访问冲突错误。

问题在link:

void link (struct node *n, int level)
{
  struct qnode *qn;
  struct qnode *current, *next;
  struct qnode nextd;
  // BUG 1 = nextd is uninitialized
  // BUG 2 - nextd is a stack-based variable, becomes junk when function exits
  next = &nextd; 
  // Becuase nextd is uninitialized, next->lnode points to garbage. Kaboom!
  (next->lnode)->data=5;
  cout << (next->lnode)->data << endl;
}