-3

I have a struct called Node. Node accepts a double and stores it into a variable named value.

I'm trying to make a new struct. My first example works, but the second doesn't. The second example doesn't give a compiler error and it builds just fine, but when I try to access a value from the node later on, it gives me -9.25596e+061.

This code works fine:

Node *firstNode; 
Node *newNode = new Node(value); 
firstNode = newNode; 

This code doesn't:

Node *firstNode; 
Node newNode(value); 
firstNode = &newNode;

I could just use the first three lines of code, but I want to know why the other code doesn't work. Is it fundamentally wrong or is the syntax just slightly off?

Pikamander2
  • 7,332
  • 3
  • 48
  • 69
  • 4
    Maybe it's all in a function and `newNode` goes out of scope in the 2nd example? – cadaniluk Nov 20 '15 at 20:23
  • 1
    We need more code. Where are you using the value? In another function? – brettwhiteman Nov 20 '15 at 20:24
  • @cad - Correct, this code is in a different function than the code that is accessing the variable. Is that a problem though? Why does the first one work then? – Pikamander2 Nov 20 '15 at 20:26
  • 1
    @Pikamander2 The first one is allocated on the heap and will stay around until you `delete` it. The second one is allocated as a local variable on the stack and will go out of scope as soon as the function returns. At that point you have an invalid pointer. – brettwhiteman Nov 20 '15 at 20:27
  • 2
    @Pikamander2 you need to understand the difference between allocating memory and using an addres of a variable. If you see that you can use both, it means, you do not have this understanding, and you really need to learn the basics. – SergeyA Nov 20 '15 at 20:27
  • 1
    @Pikamander2 read this http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/ – brettwhiteman Nov 20 '15 at 20:29

1 Answers1

3

Local variables are automatic - they go out of scope when the function returns and any further access to them (like via pointers as you did) is undefined behavior.

new allocates memory on the free store, which is independent of scopes or lifetimes. It can only be freed by delete or by the OS when the program exits.

Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67