algorithm - Unexpected global variable values; skewheap implementation in c++ -
i trying implement skewheap data structures lectures. ignoring whether algotihm works, have problem code itself. on vs 2012 code runs returns unexpected results. during debugging value of global variable (root
) changes unexpectedly. before entering insert(1)
function (line 72) values of root
expected them (key=5
, right=null
, left=null
). when stepping inside insert()
, root
value fields changes randomly. next, when reaching line 45:
node *p = &input;
root
changes values (input->key
, null
, null
). in dev c++ program shut down sigsev
. in general sistuation similar, in print()
, pointers left
, right
changes value unexpected values. reasons this?
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; struct node { int key; node* right; node* left; node(int _key, node* _right, node* _left) { key = _key; right = _right; left = _left; } }; node* root = null; node* union(node* p1, node* p2) { node* p; if (!p1) return p2; if (!p2) return p1; if (p1->key > p2->key) { p = p1; union(p1->right, p2); } else { p = p2; union(p1, p2->right); } swap(p->left, p->right); return p; } void insert(int v) { node input = node(v, null, null); node* p = &input; root = union(root, p); } void print(node* v) { if (!v) { return; } if (v->right) { print(v->right); } cout << v->key << endl; if (v->left) { print(v->left); } } int main() { insert(5); insert(1); cout << root->key; system("pause"); return 0; }
input
local scope of insert()
because declared automatic variable inside body. doesn't have dynamic storage-duration object declared new
does. if union()
method returns p2
(that is, if returns node input
), root
still pointing object still destroyed when insert()
function ends. called dangling pointer.
declare object dynamically prevent happening:
node* input = new node(v, null, null); node* p = input; root = union(root, p);
Comments
Post a Comment