简体   繁体   中英

C++ programming errror - Run time error

I got run time error while executing the below piece of c++ code. Can someone help me out why i'm getting this runtime error.

#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;


  }

In your link function, you did this:

next = &nextd;

nextd was not initialized and contains junk values when its address is assigned to next. The next lines then try to access it and that causes an access violation error.

The problem is in 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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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