0

This simple block of code is behaving in an unexpected way.

#include <iostream>
using namespace std;


class Node
{
 public:
    char* data;
    Node(char d)
    {
       data = &d;
    }
};


int main()
{
   Node NodeA = Node('c');
   cout<<*(NodeA.data)<<endl;
   return 0;
}

I was expecting to get 'c' as the output, but instead it outputs '}'. I had the feeling that it must be related to assigning the "data" pointer to an anonymous variable which is the 'c'.

I found this question discussing a similar issue.

But as it was mentioned in the top answer, the anonymous variable will only be killed if it was not bounded by a pointer referencing it by the end of the expression. Which is what I believe is not the case here as I am binding the pointer ("data") to it, but somehow it still gets killed.

I want to know what is going here that is causing the unexpected output.

omargamal8
  • 551
  • 5
  • 12
  • 3
    You're not taking a pointer to the anonymous `'c'`, you're taking a pointer to the _parameter_ `d`. The `'c'` is passed in _by value_ to your `Node(char d)`. – Steve Dec 05 '17 at 11:31
  • You call it anonymous - but the one that's of interest is `d` - which I call local. What do you think happens when your pointer when the local variable goes out of scope? – UKMonkey Dec 05 '17 at 11:32

1 Answers1

6

In your class:

Node(char d)
{
   data = &d;
}

char d is a parameter to constructor Node. The problem is that d lives only in local scope on the program stack. It ceases to exist when the code returns from constructor. data now has an address pointing somewhere in the program stack. If you try to read the data, you could read some other thing that was pushed on the stack later. If you write to this address you'll overwrite some other variables in your program. It could crash or just do something unexpected.

nio
  • 5,141
  • 2
  • 24
  • 35