0

Consider this piece of code -

#include<bits/stdc++.h>

using namespace std;

struct node{
    char symbol;
    node * left = NULL;
    node * right = NULL;
};


node * somefn(node *ptr){
    node temp;
    node temp2;
    temp.left = &temp2;
    temp.symbol = 'b';
    ptr = &temp;
    return ptr;
}

int main(){
    node *ptr;
    ptr = somefn(ptr);

    cout<<(ptr->symbol)<< "\n"; // this statement
    if(ptr->left->left != NULL) cout<<"this shldnt print";
    return 0;

}

When I execute this keeping the first cout statement I get the output -

b
this shldnt print

However, when remove the first cout statement, nothing gets printed(the second cout neither). Why this inconsistent behavior? I am using gcc version 5.4.0. I even tried this code on online ide but the same thing happened there too.

ritvix
  • 17
  • 4
  • `somefn` returns a dangling pointer to a local variable that has already been destroyed. Your program exhibits undefined behavior by way of accessing an object whose lifetime has ended. – Igor Tandetnik Mar 07 '21 at 21:24
  • Please read [Why should I **not** `#include `?](https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H.) – Ted Lyngmo Mar 07 '21 at 21:39
  • `temp.left = &temp2;` is a bug so is `ptr = &temp;` when the function ends both of these objects no longer exist however you return a pointer to the non existent object. – drescherjm Mar 07 '21 at 21:52

1 Answers1

0

There are multiple issues with your code, somefn() specifically. First this is not how pointers work and you need to create instances of "node" dynamically in somefn(). "temp" and "temp2" are local variables and they go out of scope when the function returns, meaning the node instances are created on stack and are "no longer usable" outside of somefn(). C++ specifies this as "undefined behavior" aka anything can happen case.

Other issues are you should use "#include " to introduce std::cout ("bits/" is not standard and sounds like some internal directory) and while not technically wrong in C++ you should use "nullptr" (or "0") instead of NULL.

demeter
  • 92
  • 1
  • Thanks @demeter ! I was wondering, is there any way to create instances(and not loose them after function returns) other than dynamic allocation? Also I do not want to return the node object itself( it will take time to copy, right?) – ritvix Mar 08 '21 at 06:28