繁体   English   中英

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

[英]C++ programming errror - Run time error

执行下面的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;


  }

在链接功能中,您这样做:

next = &nextd;

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

问题出在链接中:

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;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM