[英]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.