c++ - Pointers and reference issue -
i'm creating similar structure list. @ beginning of main declare null pointer. call insert() function couple of times, passing reference pointer, add new elements.
however, seems wrong. can't display list's element, std::cout
breaks program, though compiler without warning.
#include <iostream> struct node { node *p, *left, *right; int key; }; void insert(node *&root, const int key) { node newelement = {}; newelement.key = key; node *y = null; std::cout << root->key; // line while(root) { if(key == root->key) exit(exit_failure); y = root; root = (key < root->key) ? root->left : root->right; } newelement.p = y; if(!y) root = &newelement; else if(key < y->key) y->left = &newelement; else y->right = &newelement; } int main() { node *root = null; insert(root, 5); std::cout << root->key; // works if delete cout in insert() insert(root, 2); std::cout << root->key; // program breaks before line return 0; }
as can see, create new structure element in insert function , save inside root pointer. in first call, while loop isn't initiated works, , i'm able display root's element in main function.
but in second call, while loop works, , problem described.
there's wrong root->key
syntax because doesn't work if place in first call.
what's wrong, , what's reason?
also, i've seen inserting new list's elements through pointers this:
node newelement = new node(); newelement->key = 5; root->next = newelement;
is code equal to:
node newelement = {}; newelement.key = 5; root->next = &newelement;
? bit cleaner, , there wouldn't need delete memory.
the problem because passing pointer local variable out of function. dereferencing such pointers undefined behavior. should allocate newelement
new
.
this code
node newelement = {};
creates local variable newelement
. once function over, scope of newelement
ends, , memory gets destroyed. however, passing pointer destroyed memory outside function. references memory become invalid function exits.
this code, on other hand
node *newelement = new node(); // don't forget asterisk
allocates object on free store. such objects remain available until delete
them explicitly. that's why can use them after function creating them has exited. of course since newelement
pointer, need use ->
access members.
Comments
Post a Comment