0

I was trying to return a pointer to a structure from a function. I wrote the following code but it did not work and gave a segmentation fault.

#include <iostream>

using namespace std;

struct Node {
    int val;
    Node* next;
    Node(int x): val(x), next(NULL) {};
};

Node* f(int a){
    Node x = Node(10);
    return &x;
}

int main(){
    Node *x = f(10);
    cout << x->val << "\n";
    return 0;
}

Whereas the following piece of code worked fine.

#include <iostream>

using namespace std;

struct Node {
    int val;
    Node* next;
    Node(int x): val(x), next(NULL) {};
};

Node* f(int a){
    Node *x = new Node(10);
    return x;
}

int main(){
    Node *x = f(10);
    cout << x->val << "\n";
    return 0;
}

Why is the first code not working whereas the second one is working?

  • 1
    Node x = Node(10); return &x; You are passing the address of a stack based variable so the behavior will be undefined – Asesh Sep 08 '17 at 14:31
  • your first code returns a pointer to an object that is not there anymore when you try to use the pointer – 463035818_is_not_an_ai Sep 08 '17 at 14:31
  • 2
    In your first code, you are creating a Node object on Stack and the moment the function exits, it goes out of scope and thus the pointer to that memory is invalid. That's why you are getting the fault. In your second code, Node object is created on Heap, it's long living object and pointer to it will remain valid till it gets deleted explicitly by `delete` operation – Sunil Singhal Sep 08 '17 at 14:35

1 Answers1

1

You should never return a reference to a local variable unless it is dynamically allocated or a static variable since when the function returns, it is destroyed and then you will try to access an area that you have no right to.

mualloc
  • 495
  • 9
  • 24