Search code examples
c++scopepass-by-referencepass-by-value

Why does an object go out of scope when passed as a pointer, but not when it is returned


Making a very simple linked list I found myself confused about what is probably a very simple scoping concept. The first works as expected. It would seem that in the second makeNode function the node "n" is going out of scope at termination. I'm confused why this is happening.

I'm pretty sure the allocated memory is still there, and both methods have a pointer to that memory. So why is one not working?

the Program has two make node functions

#include <iostream>
using namespace std;

struct Node
{
    int value;
    Node* next;
    Node() : next(NULL){}
};

Node* makeNode1(int value)
{
    Node* n = new Node;
    n->value = value;
    return n;
}

void makeNode2(int value, Node* mountPt)
{
    Node* n = new Node;
    n->value = value;
    mountPt = n;
}

void destroyNode(Node* mountPt)
{
    if(mountPt->next != NULL)
    {
        destroyNode(mountPt->next);
        delete mountPt;
    }
}

int main() {
    Node* origin = NULL;

    // This works
    origin = makeNode1(4);

    // causes a runtime error when dereferenced
    makeNode2(4, origin);

    return 0;
}

Solution

  • For makeNode2 the pointer parameter mountPt is passed-by-value itself, then any modification on the pointer itself inside the function like mountPt = n; has nothing to do with the original argument origin.

    You can change it to pass-by-reference, i.e.

    void makeNode2(int value, Node*& mountPt)