Why return pointer to object if pointer is modified within function?









up vote
0
down vote

favorite












I found this snippet of code from GeeksForGeeks on importing nodes into a tree from a array-representation of a tree.



I tried implementing my own version of this but couldn't make it work. Then I realized that I must return Node* (in my own version: treeNode*).



Why do I have to do this If I'm already modifying the pointer (root) within the function?



From GeeksForGeeks:



// Function to insert nodes in level order 
Node* insertLevelOrder(int arr, Node* root, int i, int n)

// Base case for recursion
if (i < n)

Node* temp = newNode(arr[i]);
root = temp;

// insert left child
root->left = insertLevelOrder(arr,
root->left, 2 * i + 1, n);

// insert right child
root->right = insertLevelOrder(arr,
root->right, 2 * i + 2, n);

return root;



My Own Version:



treeNode* import_treeNode(treeNode* root, int nodes, int curr_i, int size)
if (curr_i < size)
treeNode newNode = treeNode(nodes[curr_i]);
root = &newNode;
root->left = import_treeNode(root->left, nodes, 2 * curr_i + 1, size);
root->right = import_treeNode(root->right, nodes, 2 * curr_i + 2, size);

return root;



My version does not work because it doesn't successfully return a treeNode with values set. I can verify that the treeNode constructor does work. The problem lies in root->left = import_treeNode doesn't successfully set the left node, and same for the right node.










share|improve this question





















  • the reason is that the function "insertLevelOrder" modifies value of argument pointer, not the actual pointer pointing to the bst root. to fully understand the difference you need to know the difference between "pass by value" and "pass by reference"
    – mangusta
    Nov 11 at 4:36














up vote
0
down vote

favorite












I found this snippet of code from GeeksForGeeks on importing nodes into a tree from a array-representation of a tree.



I tried implementing my own version of this but couldn't make it work. Then I realized that I must return Node* (in my own version: treeNode*).



Why do I have to do this If I'm already modifying the pointer (root) within the function?



From GeeksForGeeks:



// Function to insert nodes in level order 
Node* insertLevelOrder(int arr, Node* root, int i, int n)

// Base case for recursion
if (i < n)

Node* temp = newNode(arr[i]);
root = temp;

// insert left child
root->left = insertLevelOrder(arr,
root->left, 2 * i + 1, n);

// insert right child
root->right = insertLevelOrder(arr,
root->right, 2 * i + 2, n);

return root;



My Own Version:



treeNode* import_treeNode(treeNode* root, int nodes, int curr_i, int size)
if (curr_i < size)
treeNode newNode = treeNode(nodes[curr_i]);
root = &newNode;
root->left = import_treeNode(root->left, nodes, 2 * curr_i + 1, size);
root->right = import_treeNode(root->right, nodes, 2 * curr_i + 2, size);

return root;



My version does not work because it doesn't successfully return a treeNode with values set. I can verify that the treeNode constructor does work. The problem lies in root->left = import_treeNode doesn't successfully set the left node, and same for the right node.










share|improve this question





















  • the reason is that the function "insertLevelOrder" modifies value of argument pointer, not the actual pointer pointing to the bst root. to fully understand the difference you need to know the difference between "pass by value" and "pass by reference"
    – mangusta
    Nov 11 at 4:36












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I found this snippet of code from GeeksForGeeks on importing nodes into a tree from a array-representation of a tree.



I tried implementing my own version of this but couldn't make it work. Then I realized that I must return Node* (in my own version: treeNode*).



Why do I have to do this If I'm already modifying the pointer (root) within the function?



From GeeksForGeeks:



// Function to insert nodes in level order 
Node* insertLevelOrder(int arr, Node* root, int i, int n)

// Base case for recursion
if (i < n)

Node* temp = newNode(arr[i]);
root = temp;

// insert left child
root->left = insertLevelOrder(arr,
root->left, 2 * i + 1, n);

// insert right child
root->right = insertLevelOrder(arr,
root->right, 2 * i + 2, n);

return root;



My Own Version:



treeNode* import_treeNode(treeNode* root, int nodes, int curr_i, int size)
if (curr_i < size)
treeNode newNode = treeNode(nodes[curr_i]);
root = &newNode;
root->left = import_treeNode(root->left, nodes, 2 * curr_i + 1, size);
root->right = import_treeNode(root->right, nodes, 2 * curr_i + 2, size);

return root;



My version does not work because it doesn't successfully return a treeNode with values set. I can verify that the treeNode constructor does work. The problem lies in root->left = import_treeNode doesn't successfully set the left node, and same for the right node.










share|improve this question













I found this snippet of code from GeeksForGeeks on importing nodes into a tree from a array-representation of a tree.



I tried implementing my own version of this but couldn't make it work. Then I realized that I must return Node* (in my own version: treeNode*).



Why do I have to do this If I'm already modifying the pointer (root) within the function?



From GeeksForGeeks:



// Function to insert nodes in level order 
Node* insertLevelOrder(int arr, Node* root, int i, int n)

// Base case for recursion
if (i < n)

Node* temp = newNode(arr[i]);
root = temp;

// insert left child
root->left = insertLevelOrder(arr,
root->left, 2 * i + 1, n);

// insert right child
root->right = insertLevelOrder(arr,
root->right, 2 * i + 2, n);

return root;



My Own Version:



treeNode* import_treeNode(treeNode* root, int nodes, int curr_i, int size)
if (curr_i < size)
treeNode newNode = treeNode(nodes[curr_i]);
root = &newNode;
root->left = import_treeNode(root->left, nodes, 2 * curr_i + 1, size);
root->right = import_treeNode(root->right, nodes, 2 * curr_i + 2, size);

return root;



My version does not work because it doesn't successfully return a treeNode with values set. I can verify that the treeNode constructor does work. The problem lies in root->left = import_treeNode doesn't successfully set the left node, and same for the right node.







c++ data-structures






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 4:20









Timothy Huang

11




11











  • the reason is that the function "insertLevelOrder" modifies value of argument pointer, not the actual pointer pointing to the bst root. to fully understand the difference you need to know the difference between "pass by value" and "pass by reference"
    – mangusta
    Nov 11 at 4:36
















  • the reason is that the function "insertLevelOrder" modifies value of argument pointer, not the actual pointer pointing to the bst root. to fully understand the difference you need to know the difference between "pass by value" and "pass by reference"
    – mangusta
    Nov 11 at 4:36















the reason is that the function "insertLevelOrder" modifies value of argument pointer, not the actual pointer pointing to the bst root. to fully understand the difference you need to know the difference between "pass by value" and "pass by reference"
– mangusta
Nov 11 at 4:36




the reason is that the function "insertLevelOrder" modifies value of argument pointer, not the actual pointer pointing to the bst root. to fully understand the difference you need to know the difference between "pass by value" and "pass by reference"
– mangusta
Nov 11 at 4:36












1 Answer
1






active

oldest

votes

















up vote
1
down vote













You are returning a pointer to a local variable, whose lifetime has already ended.



treeNode* import_treeNode(treeNode* root, int nodes, int curr_i, int size)
if (curr_i < size)
// The lifetime of "newNode" begins when its constructor completes.
treeNode newNode = treeNode(nodes[curr_i]);
root = &newNode;
// Now root points at newNode.
root->left = import_treeNode(root->left, nodes, 2 * curr_i + 1, size);
root->right = import_treeNode(root->right, nodes, 2 * curr_i + 2, size);
// The above are the same as just assigning newNode.left and newNode.right.

// Here the destructor is invoked for "newNode", and its lifetime ends.

// Returns a dangling pointer, which once pointed at newNode.
// Using that pointer in almost any way results in undefined behavior.
return root;



It would be better to use a std::unique_ptr<treeNode> or std::shared_ptr<treeNode>, which are harder to accidentally leave as dangling pointers. Or if you must use raw pointers, then you would at least need to create a treeNode object using the new keyword, so that its lifetime can last longer than a function call.






share|improve this answer




















  • Why does the GeeksForGeeks version work then if it returns root, a Node* pointer, exactly like I'm doing in mine?
    – Timothy Huang
    Nov 11 at 4:41










  • @TimothyHuang We'd have to see the code to be sure, but the GeeksForGeeks code initializes a new pointer in newNode(arr[i]);. Also, notice that they have Node *temp while you have treeNode newNode -- they're initializing a pointer, while you're initializing a local variable. I'd also be really worried about whether that local variable is initialized properly.
    – John Perry
    Nov 11 at 4:42











  • @aschepler has hit the nail on the head. This is a common C++ mistake, and often hard to debug, especially for beginners. Other languages don't have this problem because everything is a reference/pointer.
    – John Perry
    Nov 11 at 4:44










  • Your code saves the address of newNode, which is the address of an object that will cease to exist as soon as you hit the } after the if. The example code does not make that mistake as it does not create a local object of type Node instead creating a local object of type Node*.
    – David Schwartz
    Nov 11 at 8:00










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













 

draft saved


draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245802%2fwhy-return-pointer-to-object-if-pointer-is-modified-within-function%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote













You are returning a pointer to a local variable, whose lifetime has already ended.



treeNode* import_treeNode(treeNode* root, int nodes, int curr_i, int size)
if (curr_i < size)
// The lifetime of "newNode" begins when its constructor completes.
treeNode newNode = treeNode(nodes[curr_i]);
root = &newNode;
// Now root points at newNode.
root->left = import_treeNode(root->left, nodes, 2 * curr_i + 1, size);
root->right = import_treeNode(root->right, nodes, 2 * curr_i + 2, size);
// The above are the same as just assigning newNode.left and newNode.right.

// Here the destructor is invoked for "newNode", and its lifetime ends.

// Returns a dangling pointer, which once pointed at newNode.
// Using that pointer in almost any way results in undefined behavior.
return root;



It would be better to use a std::unique_ptr<treeNode> or std::shared_ptr<treeNode>, which are harder to accidentally leave as dangling pointers. Or if you must use raw pointers, then you would at least need to create a treeNode object using the new keyword, so that its lifetime can last longer than a function call.






share|improve this answer




















  • Why does the GeeksForGeeks version work then if it returns root, a Node* pointer, exactly like I'm doing in mine?
    – Timothy Huang
    Nov 11 at 4:41










  • @TimothyHuang We'd have to see the code to be sure, but the GeeksForGeeks code initializes a new pointer in newNode(arr[i]);. Also, notice that they have Node *temp while you have treeNode newNode -- they're initializing a pointer, while you're initializing a local variable. I'd also be really worried about whether that local variable is initialized properly.
    – John Perry
    Nov 11 at 4:42











  • @aschepler has hit the nail on the head. This is a common C++ mistake, and often hard to debug, especially for beginners. Other languages don't have this problem because everything is a reference/pointer.
    – John Perry
    Nov 11 at 4:44










  • Your code saves the address of newNode, which is the address of an object that will cease to exist as soon as you hit the } after the if. The example code does not make that mistake as it does not create a local object of type Node instead creating a local object of type Node*.
    – David Schwartz
    Nov 11 at 8:00














up vote
1
down vote













You are returning a pointer to a local variable, whose lifetime has already ended.



treeNode* import_treeNode(treeNode* root, int nodes, int curr_i, int size)
if (curr_i < size)
// The lifetime of "newNode" begins when its constructor completes.
treeNode newNode = treeNode(nodes[curr_i]);
root = &newNode;
// Now root points at newNode.
root->left = import_treeNode(root->left, nodes, 2 * curr_i + 1, size);
root->right = import_treeNode(root->right, nodes, 2 * curr_i + 2, size);
// The above are the same as just assigning newNode.left and newNode.right.

// Here the destructor is invoked for "newNode", and its lifetime ends.

// Returns a dangling pointer, which once pointed at newNode.
// Using that pointer in almost any way results in undefined behavior.
return root;



It would be better to use a std::unique_ptr<treeNode> or std::shared_ptr<treeNode>, which are harder to accidentally leave as dangling pointers. Or if you must use raw pointers, then you would at least need to create a treeNode object using the new keyword, so that its lifetime can last longer than a function call.






share|improve this answer




















  • Why does the GeeksForGeeks version work then if it returns root, a Node* pointer, exactly like I'm doing in mine?
    – Timothy Huang
    Nov 11 at 4:41










  • @TimothyHuang We'd have to see the code to be sure, but the GeeksForGeeks code initializes a new pointer in newNode(arr[i]);. Also, notice that they have Node *temp while you have treeNode newNode -- they're initializing a pointer, while you're initializing a local variable. I'd also be really worried about whether that local variable is initialized properly.
    – John Perry
    Nov 11 at 4:42











  • @aschepler has hit the nail on the head. This is a common C++ mistake, and often hard to debug, especially for beginners. Other languages don't have this problem because everything is a reference/pointer.
    – John Perry
    Nov 11 at 4:44










  • Your code saves the address of newNode, which is the address of an object that will cease to exist as soon as you hit the } after the if. The example code does not make that mistake as it does not create a local object of type Node instead creating a local object of type Node*.
    – David Schwartz
    Nov 11 at 8:00












up vote
1
down vote










up vote
1
down vote









You are returning a pointer to a local variable, whose lifetime has already ended.



treeNode* import_treeNode(treeNode* root, int nodes, int curr_i, int size)
if (curr_i < size)
// The lifetime of "newNode" begins when its constructor completes.
treeNode newNode = treeNode(nodes[curr_i]);
root = &newNode;
// Now root points at newNode.
root->left = import_treeNode(root->left, nodes, 2 * curr_i + 1, size);
root->right = import_treeNode(root->right, nodes, 2 * curr_i + 2, size);
// The above are the same as just assigning newNode.left and newNode.right.

// Here the destructor is invoked for "newNode", and its lifetime ends.

// Returns a dangling pointer, which once pointed at newNode.
// Using that pointer in almost any way results in undefined behavior.
return root;



It would be better to use a std::unique_ptr<treeNode> or std::shared_ptr<treeNode>, which are harder to accidentally leave as dangling pointers. Or if you must use raw pointers, then you would at least need to create a treeNode object using the new keyword, so that its lifetime can last longer than a function call.






share|improve this answer












You are returning a pointer to a local variable, whose lifetime has already ended.



treeNode* import_treeNode(treeNode* root, int nodes, int curr_i, int size)
if (curr_i < size)
// The lifetime of "newNode" begins when its constructor completes.
treeNode newNode = treeNode(nodes[curr_i]);
root = &newNode;
// Now root points at newNode.
root->left = import_treeNode(root->left, nodes, 2 * curr_i + 1, size);
root->right = import_treeNode(root->right, nodes, 2 * curr_i + 2, size);
// The above are the same as just assigning newNode.left and newNode.right.

// Here the destructor is invoked for "newNode", and its lifetime ends.

// Returns a dangling pointer, which once pointed at newNode.
// Using that pointer in almost any way results in undefined behavior.
return root;



It would be better to use a std::unique_ptr<treeNode> or std::shared_ptr<treeNode>, which are harder to accidentally leave as dangling pointers. Or if you must use raw pointers, then you would at least need to create a treeNode object using the new keyword, so that its lifetime can last longer than a function call.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 11 at 4:32









aschepler

51.1k574126




51.1k574126











  • Why does the GeeksForGeeks version work then if it returns root, a Node* pointer, exactly like I'm doing in mine?
    – Timothy Huang
    Nov 11 at 4:41










  • @TimothyHuang We'd have to see the code to be sure, but the GeeksForGeeks code initializes a new pointer in newNode(arr[i]);. Also, notice that they have Node *temp while you have treeNode newNode -- they're initializing a pointer, while you're initializing a local variable. I'd also be really worried about whether that local variable is initialized properly.
    – John Perry
    Nov 11 at 4:42











  • @aschepler has hit the nail on the head. This is a common C++ mistake, and often hard to debug, especially for beginners. Other languages don't have this problem because everything is a reference/pointer.
    – John Perry
    Nov 11 at 4:44










  • Your code saves the address of newNode, which is the address of an object that will cease to exist as soon as you hit the } after the if. The example code does not make that mistake as it does not create a local object of type Node instead creating a local object of type Node*.
    – David Schwartz
    Nov 11 at 8:00
















  • Why does the GeeksForGeeks version work then if it returns root, a Node* pointer, exactly like I'm doing in mine?
    – Timothy Huang
    Nov 11 at 4:41










  • @TimothyHuang We'd have to see the code to be sure, but the GeeksForGeeks code initializes a new pointer in newNode(arr[i]);. Also, notice that they have Node *temp while you have treeNode newNode -- they're initializing a pointer, while you're initializing a local variable. I'd also be really worried about whether that local variable is initialized properly.
    – John Perry
    Nov 11 at 4:42











  • @aschepler has hit the nail on the head. This is a common C++ mistake, and often hard to debug, especially for beginners. Other languages don't have this problem because everything is a reference/pointer.
    – John Perry
    Nov 11 at 4:44










  • Your code saves the address of newNode, which is the address of an object that will cease to exist as soon as you hit the } after the if. The example code does not make that mistake as it does not create a local object of type Node instead creating a local object of type Node*.
    – David Schwartz
    Nov 11 at 8:00















Why does the GeeksForGeeks version work then if it returns root, a Node* pointer, exactly like I'm doing in mine?
– Timothy Huang
Nov 11 at 4:41




Why does the GeeksForGeeks version work then if it returns root, a Node* pointer, exactly like I'm doing in mine?
– Timothy Huang
Nov 11 at 4:41












@TimothyHuang We'd have to see the code to be sure, but the GeeksForGeeks code initializes a new pointer in newNode(arr[i]);. Also, notice that they have Node *temp while you have treeNode newNode -- they're initializing a pointer, while you're initializing a local variable. I'd also be really worried about whether that local variable is initialized properly.
– John Perry
Nov 11 at 4:42





@TimothyHuang We'd have to see the code to be sure, but the GeeksForGeeks code initializes a new pointer in newNode(arr[i]);. Also, notice that they have Node *temp while you have treeNode newNode -- they're initializing a pointer, while you're initializing a local variable. I'd also be really worried about whether that local variable is initialized properly.
– John Perry
Nov 11 at 4:42













@aschepler has hit the nail on the head. This is a common C++ mistake, and often hard to debug, especially for beginners. Other languages don't have this problem because everything is a reference/pointer.
– John Perry
Nov 11 at 4:44




@aschepler has hit the nail on the head. This is a common C++ mistake, and often hard to debug, especially for beginners. Other languages don't have this problem because everything is a reference/pointer.
– John Perry
Nov 11 at 4:44












Your code saves the address of newNode, which is the address of an object that will cease to exist as soon as you hit the } after the if. The example code does not make that mistake as it does not create a local object of type Node instead creating a local object of type Node*.
– David Schwartz
Nov 11 at 8:00




Your code saves the address of newNode, which is the address of an object that will cease to exist as soon as you hit the } after the if. The example code does not make that mistake as it does not create a local object of type Node instead creating a local object of type Node*.
– David Schwartz
Nov 11 at 8:00

















 

draft saved


draft discarded















































 


draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245802%2fwhy-return-pointer-to-object-if-pointer-is-modified-within-function%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

How to read a connectionString WITH PROVIDER in .NET Core?

Node.js Script on GitHub Pages or Amazon S3

Museum of Modern and Contemporary Art of Trento and Rovereto